stoolap 0.4.0

High-performance embedded SQL database with MVCC, time-travel queries, and full ACID compliance
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
// Copyright 2025 Stoolap Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Persistence tests for snapshot, WAL, and index recovery

use stoolap::Database;
use tempfile::tempdir;

/// Verifies that UPDATE operations are persisted correctly across database
/// restarts when snapshots exist.
#[test]
fn test_update_persistence_with_snapshot() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // First connection - create table and insert data
    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE users (
                id INTEGER PRIMARY KEY,
                name TEXT NOT NULL,
                email TEXT,
                created_at TIMESTAMP
            )",
            (),
        )
        .unwrap();

        db.execute(
            "INSERT INTO users (id, name, email, created_at)
             VALUES (1, 'John Doe', 'john@example.com', NOW())",
            (),
        )
        .unwrap();

        // Verify initial data
        let name: String = db
            .query_one("SELECT name FROM users WHERE id = 1", ())
            .unwrap();
        assert_eq!(name, "John Doe");

        db.close().unwrap();
    }

    // Second connection - update the data
    {
        let db = Database::open(&dsn).unwrap();

        // Update the name
        let result = db.execute("UPDATE users SET name = 'Jane Doe' WHERE id = 1", ());
        assert!(result.is_ok());

        // Verify update in same session
        let name: String = db
            .query_one("SELECT name FROM users WHERE id = 1", ())
            .unwrap();
        assert_eq!(name, "Jane Doe");

        db.close().unwrap();
    }

    // Third connection - verify update persisted
    {
        let db = Database::open(&dsn).unwrap();

        let name: String = db
            .query_one("SELECT name FROM users WHERE id = 1", ())
            .unwrap();

        // This is the critical test - the update should persist!
        assert_eq!(
            name, "Jane Doe",
            "UPDATE not persisted! Expected 'Jane Doe' after restart, got '{}'",
            name
        );

        // Also test multiple updates
        db.execute("UPDATE users SET name = 'Alice Smith' WHERE id = 1", ())
            .unwrap();

        db.close().unwrap();
    }

    // Fourth connection - verify second update
    {
        let db = Database::open(&dsn).unwrap();

        let name: String = db
            .query_one("SELECT name FROM users WHERE id = 1", ())
            .unwrap();

        assert_eq!(
            name, "Alice Smith",
            "Second UPDATE not persisted! Expected 'Alice Smith' after restart, got '{}'",
            name
        );

        db.close().unwrap();
    }
}

/// Tests multiple updates to the same row with snapshot persistence
#[test]
fn test_update_chain_with_snapshot() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE counter (
                id INTEGER PRIMARY KEY,
                value INTEGER NOT NULL
            )",
            (),
        )
        .unwrap();

        // Insert initial value
        db.execute("INSERT INTO counter (id, value) VALUES (1, 0)", ())
            .unwrap();

        // Perform multiple updates
        for i in 1..=5 {
            db.execute(
                &format!("UPDATE counter SET value = {} WHERE id = 1", i),
                (),
            )
            .unwrap();
        }

        // Verify final value
        let value: i64 = db
            .query_one("SELECT value FROM counter WHERE id = 1", ())
            .unwrap();
        assert_eq!(value, 5);

        db.close().unwrap();
    }

    // Reopen and verify
    {
        let db = Database::open(&dsn).unwrap();

        let value: i64 = db
            .query_one("SELECT value FROM counter WHERE id = 1", ())
            .unwrap();

        assert_eq!(
            value, 5,
            "UPDATE chain not persisted! Expected counter value 5 after restart, got {}",
            value
        );

        db.close().unwrap();
    }
}

/// Tests that both regular and unique indexes with custom names are properly
/// persisted and correctly restored after database restart.
#[test]
fn test_snapshot_index_persistence() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();

        // Create a test table
        db.execute(
            "CREATE TABLE customers (
                id INTEGER PRIMARY KEY,
                name TEXT,
                email TEXT,
                region TEXT,
                active BOOLEAN
            )",
            (),
        )
        .unwrap();

        // Insert some data
        db.execute(
            "INSERT INTO customers (id, name, email, region, active) VALUES
                (1, 'John Doe', 'john@example.com', 'North', true),
                (2, 'Jane Smith', 'jane@example.com', 'South', true),
                (3, 'Bob Johnson', 'bob@example.com', 'East', false),
                (4, 'Alice Brown', 'alice@example.com', 'West', true),
                (5, 'Charlie Wilson', 'charlie@example.com', 'North', false)",
            (),
        )
        .unwrap();

        // Create a regular index with a custom name
        db.execute("CREATE INDEX idx_customer_region ON customers(region)", ())
            .unwrap();

        // Create a unique index on email
        db.execute(
            "CREATE UNIQUE INDEX idx_customer_email ON customers(email)",
            (),
        )
        .unwrap();

        db.close().unwrap();
    }

    // Reopen the database to test persistence
    {
        let db = Database::open(&dsn).unwrap();

        // Try to insert a duplicate email to verify uniqueness is still enforced
        let result =
            db.execute("INSERT INTO customers (id, name, email, region, active) VALUES (6, 'Duplicate Email', 'john@example.com', 'South', true)", ());
        assert!(
            result.is_err(),
            "Expected unique constraint violation, but insert succeeded"
        );

        // Test successful insert with a different email
        let result = db.execute("INSERT INTO customers (id, name, email, region, active) VALUES (6, 'Mark Davis', 'mark@example.com', 'East', true)", ());
        assert!(
            result.is_ok(),
            "Failed to insert valid data after reopen: {:?}",
            result.err()
        );

        db.close().unwrap();
    }
}

/// TestOldSnapshotWithWAL tests the scenario where:
/// 1. User has an old snapshot with 100 rows
/// 2. User deletes all rows (recorded in WAL)
/// 3. No new snapshot is created before exit
/// 4. On restart, system loads old snapshot + replays WAL deletions
#[test]
fn test_old_snapshot_with_wal() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create data
    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE users (
                id INTEGER PRIMARY KEY,
                name TEXT,
                email TEXT
            )",
            (),
        )
        .unwrap();

        // Insert 100 users
        for i in 1..=100 {
            db.execute(
                &format!(
                    "INSERT INTO users (id, name, email) VALUES ({}, 'User {}', 'user{}@example.com')",
                    i, i, i
                ),
                (),
            )
            .unwrap();
        }

        db.close().unwrap();
    }

    // Session 2: Delete all data WITHOUT creating new snapshot
    {
        let db = Database::open(&dsn).unwrap();

        // Verify initial state
        let count: i64 = db.query_one("SELECT COUNT(*) FROM users", ()).unwrap();
        assert_eq!(count, 100, "Expected 100 users from snapshot");

        // Delete all users
        db.execute("DELETE FROM users", ()).unwrap();

        // Verify deletion in current session
        let count: i64 = db.query_one("SELECT COUNT(*) FROM users", ()).unwrap();
        assert_eq!(count, 0, "Expected 0 users after delete");

        db.close().unwrap();
    }

    // Session 3: Reopen and check if deletions persist
    {
        let db = Database::open(&dsn).unwrap();

        let count: i64 = db.query_one("SELECT COUNT(*) FROM users", ()).unwrap();

        // Should be 0 (WAL has DELETE operations)
        assert_eq!(
            count, 0,
            "BUG: Expected 0 users, got {} - WAL replay failed!",
            count
        );

        db.close().unwrap();
    }
}

/// TestUniqueIndexPersistence tests that unique index properties are properly preserved
/// when using CREATE UNIQUE INDEX across database reopens
#[test]
fn test_unique_index_persistence() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();

        // Create a test table
        db.execute(
            "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)",
            (),
        )
        .unwrap();

        // Create a unique index
        db.execute(
            "CREATE UNIQUE INDEX idx_users_email_unique ON users (email)",
            (),
        )
        .unwrap();

        // Insert a row to test uniqueness constraint
        db.execute(
            "INSERT INTO users (id, name, email) VALUES (1, 'User1', 'user1@example.com')",
            (),
        )
        .unwrap();

        // Try to insert a row with same email - should fail due to unique constraint
        let result = db.execute(
            "INSERT INTO users (id, name, email) VALUES (2, 'User2', 'user1@example.com')",
            (),
        );
        assert!(
            result.is_err(),
            "Inserting duplicate email should have failed"
        );

        db.close().unwrap();
    }

    // Reopen the database
    {
        let db = Database::open(&dsn).unwrap();

        // Test that uniqueness constraint is still enforced after reopen
        let result = db.execute(
            "INSERT INTO users (id, name, email) VALUES (3, 'User3', 'user1@example.com')",
            (),
        );
        assert!(
            result.is_err(),
            "Inserting duplicate email after reopen should have failed"
        );

        // Test dropping the unique index
        db.execute("DROP INDEX idx_users_email_unique ON users", ())
            .unwrap();

        db.close().unwrap();
    }

    // Reopen to verify DROP INDEX persisted
    {
        let db = Database::open(&dsn).unwrap();

        // Now we should be able to insert duplicate emails since the unique constraint is gone
        let result = db.execute(
            "INSERT INTO users (id, name, email) VALUES (3, 'User3', 'user1@example.com')",
            (),
        );
        assert!(
            result.is_ok(),
            "Inserting previously duplicate email after dropping unique index should succeed, but got: {:?}",
            result.err()
        );

        // Verify we now have two rows with the same email
        let count: i64 = db
            .query_one(
                "SELECT COUNT(*) FROM users WHERE email = 'user1@example.com'",
                (),
            )
            .unwrap();
        assert_eq!(
            count, 2,
            "Expected 2 rows with the same email after dropping unique index"
        );

        db.close().unwrap();
    }
}

/// Tests that auto-increment values are correctly persisted and restored
/// when replaying the WAL (Write-Ahead Log)
#[test]
fn test_auto_increment_wal_replay() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();

        // Create a test table with AUTO_INCREMENT
        db.execute(
            "CREATE TABLE users (
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                username TEXT NOT NULL,
                email TEXT NOT NULL
            )",
            (),
        )
        .unwrap();

        // Insert records with explicit IDs
        db.execute(
            "INSERT INTO users (id, username, email) VALUES
                (1, 'user1', 'user1@example.com'),
                (2, 'user2', 'user2@example.com'),
                (3, 'user3', 'user3@example.com')",
            (),
        )
        .unwrap();

        // Test auto-increment by inserting without providing ID
        db.execute(
            "INSERT INTO users (username, email) VALUES ('user4', 'user4@example.com')",
            (),
        )
        .unwrap();

        // Insert record with a much higher ID to advance the counter
        db.execute(
            "INSERT INTO users (id, username, email) VALUES (100, 'user100', 'user100@example.com')",
            (),
        )
        .unwrap();

        db.close().unwrap();
    }

    // Reopen the database to test WAL replay
    {
        let db = Database::open(&dsn).unwrap();

        // Insert another record without ID to check if auto-increment counter was restored correctly
        db.execute(
            "INSERT INTO users (username, email) VALUES ('user101', 'user101@example.com')",
            (),
        )
        .unwrap();

        // Verify that the auto-increment counter was correctly restored from WAL
        let max_id: i64 = db.query_one("SELECT MAX(id) FROM users", ()).unwrap();
        assert_eq!(
            max_id, 101,
            "Expected max ID to be 101 after WAL replay, got {}",
            max_id
        );

        db.close().unwrap();
    }
}

/// Tests that auto-increment values are correctly persisted and restored
/// when loading from a snapshot
#[test]
fn test_auto_increment_snapshot_loading() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();

        // Create a test table with AUTO_INCREMENT
        db.execute(
            "CREATE TABLE products (
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                name TEXT NOT NULL,
                price FLOAT NOT NULL
            )",
            (),
        )
        .unwrap();

        // Insert records with auto-incrementing IDs
        db.execute(
            "INSERT INTO products (id, name, price) VALUES
                (1, 'Product A', 10.99),
                (2, 'Product B', 20.50),
                (3, 'Product C', 30.75)",
            (),
        )
        .unwrap();

        // Insert a record with a much higher ID to advance the counter
        db.execute(
            "INSERT INTO products (id, name, price) VALUES (1000, 'Product X', 99.99)",
            (),
        )
        .unwrap();

        // Insert records without specifying ID to test auto-increment
        for i in 0..5 {
            db.execute(
                &format!(
                    "INSERT INTO products (name, price) VALUES ('Auto Product {}', {})",
                    i + 1,
                    50.0 + i as f64
                ),
                (),
            )
            .unwrap();
        }

        db.close().unwrap();
    }

    // Reopen the database to load from snapshot/WAL
    {
        let db = Database::open(&dsn).unwrap();

        // Insert another record without ID to test if auto-increment counter was restored
        db.execute(
            "INSERT INTO products (name, price) VALUES ('Product After Snapshot', 200.00)",
            (),
        )
        .unwrap();

        // Verify the auto-increment counter was correctly restored
        let max_id: i64 = db.query_one("SELECT MAX(id) FROM products", ()).unwrap();
        assert!(
            max_id >= 1000,
            "Expected max ID to be at least 1000, got {}",
            max_id
        );

        // Check the count of records in the products table
        let product_count: i64 = db.query_one("SELECT COUNT(*) FROM products", ()).unwrap();
        assert_eq!(
            product_count,
            10, // 4 explicit + 5 auto + 1 after reopen
            "Expected 10 products, got {}",
            product_count
        );

        db.close().unwrap();
    }
}

/// Tests multiple tables with mixed operations persistence
#[test]
fn test_multi_table_mixed_operations_persistence() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create tables, indexes, and insert data
    {
        let db = Database::open(&dsn).unwrap();

        // Create users table with unique index
        db.execute(
            "CREATE TABLE users (
                id INTEGER PRIMARY KEY,
                name TEXT NOT NULL,
                email TEXT NOT NULL
            )",
            (),
        )
        .unwrap();
        db.execute("CREATE UNIQUE INDEX idx_email ON users(email)", ())
            .unwrap();

        // Create orders table
        db.execute(
            "CREATE TABLE orders (
                id INTEGER PRIMARY KEY,
                user_id INTEGER NOT NULL,
                amount FLOAT NOT NULL,
                status TEXT
            )",
            (),
        )
        .unwrap();
        db.execute("CREATE INDEX idx_user_id ON orders(user_id)", ())
            .unwrap();

        // Insert users
        for i in 1..=5 {
            db.execute(
                &format!(
                    "INSERT INTO users (id, name, email) VALUES ({}, 'User {}', 'user{}@example.com')",
                    i, i, i
                ),
                (),
            )
            .unwrap();
        }

        // Insert orders
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO orders (id, user_id, amount, status) VALUES ({}, {}, {}, 'pending')",
                    i,
                    (i % 5) + 1,
                    i as f64 * 10.0
                ),
                (),
            )
            .unwrap();
        }

        db.close().unwrap();
    }

    // Session 2: Update and delete operations
    {
        let db = Database::open(&dsn).unwrap();

        // Verify data loaded
        let user_count: i64 = db.query_one("SELECT COUNT(*) FROM users", ()).unwrap();
        assert_eq!(user_count, 5);

        let order_count: i64 = db.query_one("SELECT COUNT(*) FROM orders", ()).unwrap();
        assert_eq!(order_count, 10);

        // Update some orders
        db.execute("UPDATE orders SET status = 'completed' WHERE id <= 5", ())
            .unwrap();

        // Delete some orders
        db.execute("DELETE FROM orders WHERE id > 8", ()).unwrap();

        // Verify changes
        let completed_count: i64 = db
            .query_one("SELECT COUNT(*) FROM orders WHERE status = 'completed'", ())
            .unwrap();
        assert_eq!(completed_count, 5);

        let remaining_count: i64 = db.query_one("SELECT COUNT(*) FROM orders", ()).unwrap();
        assert_eq!(remaining_count, 8);

        db.close().unwrap();
    }

    // Session 3: Verify all changes persisted
    {
        let db = Database::open(&dsn).unwrap();

        // Verify users
        let user_count: i64 = db.query_one("SELECT COUNT(*) FROM users", ()).unwrap();
        assert_eq!(user_count, 5, "User count should be 5");

        // Verify orders
        let order_count: i64 = db.query_one("SELECT COUNT(*) FROM orders", ()).unwrap();
        assert_eq!(order_count, 8, "Order count should be 8 after delete");

        // Verify update persisted
        let completed_count: i64 = db
            .query_one("SELECT COUNT(*) FROM orders WHERE status = 'completed'", ())
            .unwrap();
        assert_eq!(completed_count, 5, "Completed orders should be 5");

        // Verify unique index still works
        let result = db.execute(
            "INSERT INTO users (id, name, email) VALUES (10, 'Duplicate', 'user1@example.com')",
            (),
        );
        assert!(
            result.is_err(),
            "Unique constraint should still be enforced"
        );

        db.close().unwrap();
    }
}

/// Test transaction rollback is not persisted
/// This tests that rolled back transactions don't affect persistence
#[test]
fn test_rollback_not_persisted() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE test_data (
                id INTEGER PRIMARY KEY,
                value TEXT
            )",
            (),
        )
        .unwrap();

        // Insert initial data (this will be committed)
        db.execute(
            "INSERT INTO test_data (id, value) VALUES (1, 'committed')",
            (),
        )
        .unwrap();

        // Start a transaction, insert, then rollback
        db.execute("BEGIN TRANSACTION", ()).unwrap();
        db.execute(
            "INSERT INTO test_data (id, value) VALUES (2, 'rolled_back')",
            (),
        )
        .unwrap();
        db.execute("ROLLBACK", ()).unwrap();

        // Verify rollback worked in current session
        let count: i64 = db.query_one("SELECT COUNT(*) FROM test_data", ()).unwrap();
        assert_eq!(count, 1, "Should only have 1 row after rollback");

        db.close().unwrap();
    }

    // Reopen and verify rollback was not persisted
    {
        let db = Database::open(&dsn).unwrap();

        let count: i64 = db.query_one("SELECT COUNT(*) FROM test_data", ()).unwrap();
        assert_eq!(count, 1, "Should still have only 1 row after reopen");

        let value: String = db
            .query_one("SELECT value FROM test_data WHERE id = 1", ())
            .unwrap();
        assert_eq!(value, "committed");

        db.close().unwrap();
    }
}

/// Test that updates to same row multiple times across sessions persist correctly
#[test]
fn test_same_row_updates_across_sessions() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create and insert (use INTEGER PRIMARY KEY as required by stoolap)
    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE config (id INTEGER PRIMARY KEY, config_key TEXT, config_value TEXT)",
            (),
        )
        .unwrap();
        db.execute(
            "INSERT INTO config (id, config_key, config_value) VALUES (1, 'setting', 'value1')",
            (),
        )
        .unwrap();
        db.close().unwrap();
    }

    // Session 2: First update
    {
        let db = Database::open(&dsn).unwrap();
        let value: String = db
            .query_one(
                "SELECT config_value FROM config WHERE config_key = 'setting'",
                (),
            )
            .unwrap();
        assert_eq!(value, "value1");

        db.execute(
            "UPDATE config SET config_value = 'value2' WHERE config_key = 'setting'",
            (),
        )
        .unwrap();
        db.close().unwrap();
    }

    // Session 3: Second update
    {
        let db = Database::open(&dsn).unwrap();
        let value: String = db
            .query_one(
                "SELECT config_value FROM config WHERE config_key = 'setting'",
                (),
            )
            .unwrap();
        assert_eq!(value, "value2");

        db.execute(
            "UPDATE config SET config_value = 'value3' WHERE config_key = 'setting'",
            (),
        )
        .unwrap();
        db.close().unwrap();
    }

    // Session 4: Verify final state
    {
        let db = Database::open(&dsn).unwrap();
        let value: String = db
            .query_one(
                "SELECT config_value FROM config WHERE config_key = 'setting'",
                (),
            )
            .unwrap();
        assert_eq!(
            value, "value3",
            "Final value should be 'value3' after multiple session updates"
        );
        db.close().unwrap();
    }
}

/// Test delete then insert same key pattern
#[test]
fn test_delete_then_insert_same_key() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create, insert, delete
    {
        let db = Database::open(&dsn).unwrap();
        db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT)", ())
            .unwrap();
        db.execute("INSERT INTO items (id, name) VALUES (1, 'original')", ())
            .unwrap();
        db.execute("DELETE FROM items WHERE id = 1", ()).unwrap();

        let count: i64 = db.query_one("SELECT COUNT(*) FROM items", ()).unwrap();
        assert_eq!(count, 0);

        db.close().unwrap();
    }

    // Session 2: Insert same key with new value
    {
        let db = Database::open(&dsn).unwrap();

        let count: i64 = db.query_one("SELECT COUNT(*) FROM items", ()).unwrap();
        assert_eq!(count, 0, "Should have 0 items after delete");

        db.execute("INSERT INTO items (id, name) VALUES (1, 'new_value')", ())
            .unwrap();
        db.close().unwrap();
    }

    // Session 3: Verify new value persisted
    {
        let db = Database::open(&dsn).unwrap();

        let count: i64 = db.query_one("SELECT COUNT(*) FROM items", ()).unwrap();
        assert_eq!(count, 1);

        let name: String = db
            .query_one("SELECT name FROM items WHERE id = 1", ())
            .unwrap();
        assert_eq!(name, "new_value");

        db.close().unwrap();
    }
}

/// Verifies that unique constraints are enforced after database restart
/// without needing to SELECT rows first to load them into memory.
#[test]
fn test_unique_index_bug() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // First database connection - create table, index, and insert data
    {
        let db = Database::open(&dsn).unwrap();

        // Create a test table
        db.execute(
            "CREATE TABLE users (
                id INTEGER PRIMARY KEY,
                username TEXT,
                email TEXT
            )",
            (),
        )
        .unwrap();

        // Create a unique index on email
        db.execute("CREATE UNIQUE INDEX idx_users_email ON users(email)", ())
            .unwrap();

        // Insert some data
        db.execute(
            "INSERT INTO users (id, username, email) VALUES
                (1, 'user1', 'user1@example.com'),
                (2, 'user2', 'user2@example.com'),
                (3, 'user3', 'user3@example.com')",
            (),
        )
        .unwrap();

        // Verify uniqueness constraint works before restart
        let result = db.execute(
            "INSERT INTO users (id, username, email) VALUES (4, 'duplicate', 'user1@example.com')",
            (),
        );
        assert!(
            result.is_err(),
            "Expected unique constraint violation, but insert succeeded"
        );

        db.close().unwrap();
    }

    // Reopen the database
    {
        let db = Database::open(&dsn).unwrap();

        // WITHOUT accessing any rows first, try to insert a duplicate email
        // This should fail immediately - unique constraint should be enforced
        let result = db.execute(
            "INSERT INTO users (id, username, email) VALUES (4, 'duplicate', 'user1@example.com')",
            (),
        );
        assert!(
            result.is_err(),
            "Unique constraint should be enforced after restart without SELECT"
        );

        // Now verify the data is correct by selecting
        let count: i64 = db.query_one("SELECT COUNT(*) FROM users", ()).unwrap();
        assert_eq!(count, 3, "Should have 3 users");

        // Try to insert another duplicate - should also fail
        let result = db.execute(
            "INSERT INTO users (id, username, email) VALUES (5, 'another_duplicate', 'user2@example.com')",
            (),
        );
        assert!(
            result.is_err(),
            "Unique constraint should still be enforced"
        );

        db.close().unwrap();
    }
}

/// Tests index name preservation and persistence without the complexities
/// of database reopening
#[test]
fn test_index_direct_create() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // First connection
    {
        let db = Database::open(&dsn).unwrap();

        // Create a test table
        db.execute(
            "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)",
            (),
        )
        .unwrap();

        // Create an index with a special name
        db.execute("CREATE INDEX idx_users_email ON users (email)", ())
            .unwrap();

        // Try to create a duplicate index - this should fail
        let result = db.execute("CREATE INDEX idx_users_email ON users (email)", ());
        assert!(
            result.is_err(),
            "Creating duplicate index should have failed"
        );

        db.close().unwrap();
    }

    // Reopen the database to test persistence
    {
        let db = Database::open(&dsn).unwrap();

        // Try to create the same index again - should fail since it already exists
        let result = db.execute("CREATE INDEX idx_users_email ON users (email)", ());
        assert!(
            result.is_err(),
            "Creating duplicate index after reopen should have failed"
        );

        // Test dropping the index
        db.execute("DROP INDEX idx_users_email ON users", ())
            .unwrap();

        // Now we should be able to create it again
        db.execute("CREATE INDEX idx_users_email ON users (email)", ())
            .unwrap();

        db.close().unwrap();
    }

    // Verify drop and recreate persisted
    {
        let db = Database::open(&dsn).unwrap();

        // Index should exist, so creating it should fail
        let result = db.execute("CREATE INDEX idx_users_email ON users (email)", ());
        assert!(
            result.is_err(),
            "Index should exist after reopen, create should fail"
        );

        db.close().unwrap();
    }
}

/// Tests CREATE/DROP INDEX IF EXISTS operations and verifies that indexes
/// are properly preserved across database reopens
#[test]
fn test_index_if_exists_operations() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // First database connection
    {
        let db = Database::open(&dsn).unwrap();

        // Create a test table
        db.execute(
            "CREATE TABLE products (
                id INTEGER PRIMARY KEY,
                name TEXT,
                price FLOAT,
                category TEXT
            )",
            (),
        )
        .unwrap();

        // Insert some data
        db.execute(
            "INSERT INTO products (id, name, price, category) VALUES
                (1, 'Laptop', 999.99, 'Electronics'),
                (2, 'Smartphone', 599.99, 'Electronics'),
                (3, 'Headphones', 149.99, 'Accessories'),
                (4, 'Backpack', 79.99, 'Accessories'),
                (5, 'Monitor', 349.99, 'Electronics')",
            (),
        )
        .unwrap();

        // Test 1: Create a new index with IF NOT EXISTS (should succeed)
        db.execute(
            "CREATE INDEX IF NOT EXISTS idx_category ON products(category)",
            (),
        )
        .unwrap();

        // Test 2: Create the same index again with IF NOT EXISTS (should not error)
        let result = db.execute(
            "CREATE INDEX IF NOT EXISTS idx_category ON products(category)",
            (),
        );
        assert!(
            result.is_ok(),
            "Creating existing index with IF NOT EXISTS should not error: {:?}",
            result.err()
        );

        // Test 3: Create a unique index with IF NOT EXISTS
        db.execute(
            "CREATE UNIQUE INDEX IF NOT EXISTS idx_name ON products(name)",
            (),
        )
        .unwrap();

        db.close().unwrap();
    }

    // Reopen the database
    {
        let db = Database::open(&dsn).unwrap();

        // Test 4: Indexes should be preserved after reopen
        // Creating them again with IF NOT EXISTS should not error
        let result = db.execute(
            "CREATE INDEX IF NOT EXISTS idx_category ON products(category)",
            (),
        );
        assert!(
            result.is_ok(),
            "Creating existing index with IF NOT EXISTS after reopen should not error"
        );

        let result = db.execute(
            "CREATE UNIQUE INDEX IF NOT EXISTS idx_name ON products(name)",
            (),
        );
        assert!(
            result.is_ok(),
            "Creating existing unique index with IF NOT EXISTS after reopen should not error"
        );

        // Verify unique constraint still works
        let result = db.execute(
            "INSERT INTO products (id, name, price, category) VALUES (6, 'Laptop', 1299.99, 'Electronics')",
            (),
        );
        assert!(
            result.is_err(),
            "Unique constraint on name should still be enforced after reopen"
        );

        // Test 5: Test DROP INDEX IF EXISTS on an existing index
        db.execute("DROP INDEX IF EXISTS idx_category ON products", ())
            .unwrap();

        // Test 6: Test DROP INDEX IF EXISTS on a non-existing index (should not error)
        let result = db.execute("DROP INDEX IF EXISTS idx_nonexistent ON products", ());
        assert!(
            result.is_ok(),
            "DROP INDEX IF EXISTS on non-existing index should not error: {:?}",
            result.err()
        );

        // Verify idx_category is gone - creating it should succeed
        db.execute("CREATE INDEX idx_category ON products(category)", ())
            .unwrap();

        db.close().unwrap();
    }
}

/// Tests that index names are properly preserved when using
/// CREATE INDEX IF NOT EXISTS across database reopens
#[test]
fn test_index_name_persistence() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // First connection - create table and index
    {
        let db = Database::open(&dsn).unwrap();

        // Create a test table
        db.execute(
            "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)",
            (),
        )
        .unwrap();

        // Create an index with a special name using IF NOT EXISTS
        db.execute(
            "CREATE INDEX IF NOT EXISTS idx_users_email ON users (email)",
            (),
        )
        .unwrap();

        db.close().unwrap();
    }

    // Reopen the database
    {
        let db = Database::open(&dsn).unwrap();

        // Try to create the same index again with IF NOT EXISTS - should not error
        let result = db.execute(
            "CREATE INDEX IF NOT EXISTS idx_users_email ON users (email)",
            (),
        );
        assert!(
            result.is_ok(),
            "Creating existing index with IF NOT EXISTS after reopen should not error: {:?}",
            result.err()
        );

        // Verify the index works by trying to create another index on same column
        // without IF NOT EXISTS - should fail because idx_users_email exists
        let result = db.execute("CREATE INDEX idx_users_email ON users (email)", ());
        assert!(
            result.is_err(),
            "Creating duplicate index without IF NOT EXISTS should fail"
        );

        db.close().unwrap();
    }

    // Third connection - test that we can still use the index
    {
        let db = Database::open(&dsn).unwrap();

        // Insert some data
        db.execute(
            "INSERT INTO users (id, name, email) VALUES
                (1, 'John', 'john@example.com'),
                (2, 'Jane', 'jane@example.com')",
            (),
        )
        .unwrap();

        // Query using the indexed column
        let count: i64 = db
            .query_one(
                "SELECT COUNT(*) FROM users WHERE email = 'john@example.com'",
                (),
            )
            .unwrap();
        assert_eq!(count, 1, "Should find 1 user with email john@example.com");

        db.close().unwrap();
    }
}

/// Tests that all data types are correctly persisted and restored
/// through WAL and snapshots.
#[test]
fn test_data_type_persistence() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create table with all data types and insert data
    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE all_types (
                id INTEGER PRIMARY KEY,
                int_val INTEGER,
                float_val FLOAT,
                text_val TEXT,
                bool_val BOOLEAN,
                timestamp_val TIMESTAMP,
                date_val DATE,
                time_val TIME,
                json_val JSON
            )",
            (),
        )
        .unwrap();

        // Insert row with all data types
        db.execute(
            "INSERT INTO all_types (id, int_val, float_val, text_val, bool_val, timestamp_val, date_val, time_val, json_val)
             VALUES (1, 42, 3.5, 'hello world', true, '2025-04-25 14:30:00', '2025-04-25', '14:30:00', '{\"key\": \"value\"}')",
            (),
        )
        .unwrap();

        // Insert row with NULL values
        db.execute(
            "INSERT INTO all_types (id, int_val, float_val, text_val, bool_val, timestamp_val, date_val, time_val, json_val)
             VALUES (2, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
            (),
        )
        .unwrap();

        // Insert row with negative and edge values
        // Note: Using i64::MIN + 1 because the parser can't handle i64::MIN directly
        // (it parses the positive part first which overflows)
        db.execute(
            "INSERT INTO all_types (id, int_val, float_val, text_val, bool_val, timestamp_val, date_val, time_val, json_val)
             VALUES (3, -9223372036854775807, -0.00001, '', false, '1970-01-01 00:00:00', '1970-01-01', '00:00:00', '[]')",
            (),
        )
        .unwrap();

        db.close().unwrap();
    }

    // Session 2: Reopen and verify all data types persisted correctly
    {
        let db = Database::open(&dsn).unwrap();

        // Verify count
        let count: i64 = db.query_one("SELECT COUNT(*) FROM all_types", ()).unwrap();
        assert_eq!(count, 3, "Should have 3 rows");

        // Verify integer value
        let int_val: i64 = db
            .query_one("SELECT int_val FROM all_types WHERE id = 1", ())
            .unwrap();
        assert_eq!(int_val, 42, "Integer value mismatch");

        // Verify float value (with tolerance)
        let float_val: f64 = db
            .query_one("SELECT float_val FROM all_types WHERE id = 1", ())
            .unwrap();
        assert!(
            (float_val - 3.5).abs() < 0.00001,
            "Float value mismatch: {}",
            float_val
        );

        // Verify text value
        let text_val: String = db
            .query_one("SELECT text_val FROM all_types WHERE id = 1", ())
            .unwrap();
        assert_eq!(text_val, "hello world", "Text value mismatch");

        // Verify boolean value
        let bool_val: bool = db
            .query_one("SELECT bool_val FROM all_types WHERE id = 1", ())
            .unwrap();
        assert!(bool_val, "Boolean value mismatch");

        // Verify JSON value
        let json_val: String = db
            .query_one("SELECT json_val FROM all_types WHERE id = 1", ())
            .unwrap();
        assert!(
            json_val.contains("key") && json_val.contains("value"),
            "JSON value mismatch: {}",
            json_val
        );

        // Verify NULL values using IS NULL
        let null_count: i64 = db
            .query_one("SELECT COUNT(*) FROM all_types WHERE int_val IS NULL", ())
            .unwrap();
        assert_eq!(null_count, 1, "Should have 1 row with NULL int_val");

        // Verify negative integer (i64::MIN + 1)
        let neg_int: i64 = db
            .query_one("SELECT int_val FROM all_types WHERE id = 3", ())
            .unwrap();
        assert_eq!(
            neg_int, -9223372036854775807i64,
            "Negative integer mismatch"
        );

        // Verify empty string
        let empty_str: String = db
            .query_one("SELECT text_val FROM all_types WHERE id = 3", ())
            .unwrap();
        assert_eq!(empty_str, "", "Empty string mismatch");

        // Verify false boolean
        let false_bool: bool = db
            .query_one("SELECT bool_val FROM all_types WHERE id = 3", ())
            .unwrap();
        assert!(!false_bool, "False boolean mismatch");

        db.close().unwrap();
    }
}

/// Tests that transactions are properly isolated in the WAL, with commits
/// persisted and rollbacks not persisted.
#[test]
fn test_wal_transaction_isolation() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create table and test committed vs rolled back transactions
    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE txn_test (
                id INTEGER PRIMARY KEY,
                value TEXT,
                source TEXT
            )",
            (),
        )
        .unwrap();

        // Committed transaction 1
        db.execute("BEGIN TRANSACTION", ()).unwrap();
        db.execute(
            "INSERT INTO txn_test (id, value, source) VALUES (1, 'committed1', 'txn1')",
            (),
        )
        .unwrap();
        db.execute(
            "INSERT INTO txn_test (id, value, source) VALUES (2, 'committed2', 'txn1')",
            (),
        )
        .unwrap();
        db.execute("COMMIT", ()).unwrap();

        // Rolled back transaction 2
        db.execute("BEGIN TRANSACTION", ()).unwrap();
        db.execute(
            "INSERT INTO txn_test (id, value, source) VALUES (3, 'rolled_back', 'txn2')",
            (),
        )
        .unwrap();
        db.execute("ROLLBACK", ()).unwrap();

        // Committed transaction 3
        db.execute("BEGIN TRANSACTION", ()).unwrap();
        db.execute(
            "INSERT INTO txn_test (id, value, source) VALUES (4, 'committed3', 'txn3')",
            (),
        )
        .unwrap();
        db.execute("COMMIT", ()).unwrap();

        // Verify before close
        let count: i64 = db.query_one("SELECT COUNT(*) FROM txn_test", ()).unwrap();
        assert_eq!(count, 3, "Should have 3 rows (2 from txn1, 1 from txn3)");

        db.close().unwrap();
    }

    // Session 2: Verify only committed transactions are persisted
    {
        let db = Database::open(&dsn).unwrap();

        // Verify total count
        let count: i64 = db.query_one("SELECT COUNT(*) FROM txn_test", ()).unwrap();
        assert_eq!(
            count, 3,
            "Should have 3 rows after reopen (rolled back transaction should not be persisted)"
        );

        // Verify txn1 rows
        let txn1_count: i64 = db
            .query_one("SELECT COUNT(*) FROM txn_test WHERE source = 'txn1'", ())
            .unwrap();
        assert_eq!(txn1_count, 2, "Should have 2 rows from txn1");

        // Verify no rolled back rows
        let txn2_count: i64 = db
            .query_one("SELECT COUNT(*) FROM txn_test WHERE source = 'txn2'", ())
            .unwrap();
        assert_eq!(txn2_count, 0, "Should have 0 rows from txn2 (rolled back)");

        // Verify txn3 row
        let txn3_count: i64 = db
            .query_one("SELECT COUNT(*) FROM txn_test WHERE source = 'txn3'", ())
            .unwrap();
        assert_eq!(txn3_count, 1, "Should have 1 row from txn3");

        db.close().unwrap();
    }
}

/// Tests that DDL operations (CREATE TABLE, DROP TABLE, etc.) are properly
/// persisted through WAL.
#[test]
fn test_ddl_operations_persistence() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create multiple tables with various structures
    {
        let db = Database::open(&dsn).unwrap();

        // Create first table
        db.execute(
            "CREATE TABLE table1 (
                id INTEGER PRIMARY KEY,
                name TEXT NOT NULL,
                value INTEGER
            )",
            (),
        )
        .unwrap();

        // Insert some data
        db.execute(
            "INSERT INTO table1 (id, name, value) VALUES (1, 'test1', 100)",
            (),
        )
        .unwrap();

        // Create second table
        db.execute(
            "CREATE TABLE table2 (
                id INTEGER PRIMARY KEY,
                data TEXT,
                is_active BOOLEAN
            )",
            (),
        )
        .unwrap();

        // Insert data into second table
        db.execute(
            "INSERT INTO table2 (id, data, is_active) VALUES (1, 'data1', true)",
            (),
        )
        .unwrap();

        // Create third table and then drop it
        db.execute(
            "CREATE TABLE table3 (id INTEGER PRIMARY KEY, temp TEXT)",
            (),
        )
        .unwrap();
        db.execute("INSERT INTO table3 (id, temp) VALUES (1, 'temporary')", ())
            .unwrap();
        db.execute("DROP TABLE table3", ()).unwrap();

        db.close().unwrap();
    }

    // Session 2: Verify DDL operations were persisted correctly
    {
        let db = Database::open(&dsn).unwrap();

        // Verify table1 exists and has data
        let count1: i64 = db.query_one("SELECT COUNT(*) FROM table1", ()).unwrap();
        assert_eq!(count1, 1, "table1 should have 1 row");

        let name: String = db
            .query_one("SELECT name FROM table1 WHERE id = 1", ())
            .unwrap();
        assert_eq!(name, "test1", "table1 name mismatch");

        // Verify table2 exists and has data
        let count2: i64 = db.query_one("SELECT COUNT(*) FROM table2", ()).unwrap();
        assert_eq!(count2, 1, "table2 should have 1 row");

        // Verify table3 does NOT exist (was dropped)
        let result = db.execute("SELECT COUNT(*) FROM table3", ());
        assert!(result.is_err(), "table3 should not exist (was dropped)");

        db.close().unwrap();
    }
}

/// Tests recovery scenarios where we have a checkpoint and additional
/// WAL entries after the checkpoint.
#[test]
fn test_checkpoint_recovery() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create data that will be included in a checkpoint
    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE checkpoint_test (
                id INTEGER PRIMARY KEY,
                phase TEXT,
                value INTEGER
            )",
            (),
        )
        .unwrap();

        // Insert initial data (will be in checkpoint)
        for i in 1..=5 {
            db.execute(
                &format!(
                    "INSERT INTO checkpoint_test (id, phase, value) VALUES ({}, 'initial', {})",
                    i,
                    i * 10
                ),
                (),
            )
            .unwrap();
        }

        db.close().unwrap();
    }

    // Session 2: Add more data after checkpoint, then close
    {
        let db = Database::open(&dsn).unwrap();

        // Verify initial data
        let initial_count: i64 = db
            .query_one(
                "SELECT COUNT(*) FROM checkpoint_test WHERE phase = 'initial'",
                (),
            )
            .unwrap();
        assert_eq!(initial_count, 5, "Should have 5 initial rows");

        // Add more data (will be in WAL only after last checkpoint)
        for i in 6..=10 {
            db.execute(
                &format!(
                    "INSERT INTO checkpoint_test (id, phase, value) VALUES ({}, 'after_checkpoint', {})",
                    i,
                    i * 10
                ),
                (),
            )
            .unwrap();
        }

        // Update some existing rows
        db.execute(
            "UPDATE checkpoint_test SET value = value + 100 WHERE id <= 3",
            (),
        )
        .unwrap();

        // Delete one row
        db.execute("DELETE FROM checkpoint_test WHERE id = 4", ())
            .unwrap();

        db.close().unwrap();
    }

    // Session 3: Verify all changes (checkpoint + WAL replay) are recovered
    {
        let db = Database::open(&dsn).unwrap();

        // Verify total count (10 inserted - 1 deleted = 9)
        let total_count: i64 = db
            .query_one("SELECT COUNT(*) FROM checkpoint_test", ())
            .unwrap();
        assert_eq!(total_count, 9, "Should have 9 rows (10 - 1 deleted)");

        // Verify initial rows (minus deleted one)
        let initial_count: i64 = db
            .query_one(
                "SELECT COUNT(*) FROM checkpoint_test WHERE phase = 'initial'",
                (),
            )
            .unwrap();
        assert_eq!(
            initial_count, 4,
            "Should have 4 initial rows (5 - 1 deleted)"
        );

        // Verify after-checkpoint rows
        let after_count: i64 = db
            .query_one(
                "SELECT COUNT(*) FROM checkpoint_test WHERE phase = 'after_checkpoint'",
                (),
            )
            .unwrap();
        assert_eq!(after_count, 5, "Should have 5 after-checkpoint rows");

        // Verify updates were persisted (rows 1-3 should have value + 100)
        let updated_value: i64 = db
            .query_one("SELECT value FROM checkpoint_test WHERE id = 1", ())
            .unwrap();
        assert_eq!(
            updated_value, 110,
            "Updated value for id=1 should be 110 (10 + 100)"
        );

        // Verify row 4 was deleted
        let deleted_count: i64 = db
            .query_one("SELECT COUNT(*) FROM checkpoint_test WHERE id = 4", ())
            .unwrap();
        assert_eq!(deleted_count, 0, "Row with id=4 should be deleted");

        db.close().unwrap();
    }
}

/// Tests that database maintains consistency even with concurrent operations
/// and multiple session reopens.
#[test]
fn test_consistent_checkpoint_behavior() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Initial setup
    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE consistency_test (
                id INTEGER PRIMARY KEY,
                counter INTEGER NOT NULL DEFAULT 0,
                updated_at TIMESTAMP
            )",
            (),
        )
        .unwrap();

        // Insert initial row
        db.execute(
            "INSERT INTO consistency_test (id, counter, updated_at) VALUES (1, 0, NOW())",
            (),
        )
        .unwrap();

        db.close().unwrap();
    }

    // Multiple sessions incrementing the counter
    for session in 1..=5 {
        let db = Database::open(&dsn).unwrap();

        // Read current value
        let current: i64 = db
            .query_one("SELECT counter FROM consistency_test WHERE id = 1", ())
            .unwrap();

        // Increment and update
        db.execute(
            &format!(
                "UPDATE consistency_test SET counter = {}, updated_at = NOW() WHERE id = 1",
                current + 1
            ),
            (),
        )
        .unwrap();

        // Verify within session
        let new_value: i64 = db
            .query_one("SELECT counter FROM consistency_test WHERE id = 1", ())
            .unwrap();
        assert_eq!(
            new_value, session as i64,
            "Counter should be {} in session {}",
            session, session
        );

        db.close().unwrap();
    }

    // Final verification
    {
        let db = Database::open(&dsn).unwrap();

        let final_value: i64 = db
            .query_one("SELECT counter FROM consistency_test WHERE id = 1", ())
            .unwrap();
        assert_eq!(
            final_value, 5,
            "Final counter value should be 5 after 5 sessions"
        );

        db.close().unwrap();
    }
}

// =============================================================================
// PERSISTENCE BUG VERIFICATION TESTS
// These tests verify known persistence issues that need to be fixed
// =============================================================================

/// Test that VIEWs ARE properly persisted after database restart.
/// FIXED: create_view() and drop_view() now record to WAL, apply_wal_entry() handles CreateView/DropView.
#[test]
fn test_view_persistence() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create table and view
    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE view_source (id INTEGER PRIMARY KEY, name TEXT)",
            (),
        )
        .unwrap();

        db.execute(
            "INSERT INTO view_source VALUES (1, 'Alice'), (2, 'Bob')",
            (),
        )
        .unwrap();

        db.execute(
            "CREATE VIEW test_view AS SELECT id, UPPER(name) as upper_name FROM view_source",
            (),
        )
        .unwrap();

        // Verify view works in this session
        let count: i64 = db.query_one("SELECT COUNT(*) FROM test_view", ()).unwrap();
        assert_eq!(count, 2, "View should return 2 rows");

        db.close().unwrap();
    }

    // Session 2: Try to use the view - THIS WILL FAIL because views aren't persisted
    {
        let db = Database::open(&dsn).unwrap();

        // This query will fail because the view doesn't exist after restart
        let _count: i64 = db.query_one("SELECT COUNT(*) FROM test_view", ()).unwrap();

        db.close().unwrap();
    }
}

/// Test that ALTER TABLE ADD COLUMN IS persisted after database restart.
/// Schema modifications via ADD COLUMN are recorded to WAL and replayed.
/// Note: Backfilling of existing rows with default values may not persist across restarts.
#[test]
fn test_alter_table_add_column_persistence() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create table and add column
    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE alter_test (id INTEGER PRIMARY KEY, name TEXT)",
            (),
        )
        .unwrap();

        db.execute("INSERT INTO alter_test VALUES (1, 'test')", ())
            .unwrap();

        // Add a new column
        db.execute(
            "ALTER TABLE alter_test ADD COLUMN new_column INTEGER DEFAULT 42",
            (),
        )
        .unwrap();

        // Verify column exists in this session
        let value: i64 = db
            .query_one("SELECT new_column FROM alter_test WHERE id = 1", ())
            .unwrap();
        assert_eq!(value, 42, "New column should have default value");

        // Insert a new row after column addition
        db.execute("INSERT INTO alter_test VALUES (2, 'second', 100)", ())
            .unwrap();

        db.close().unwrap();
    }

    // Session 2: Verify schema was persisted
    {
        let db = Database::open(&dsn).unwrap();

        // The column should exist after restart (schema was persisted)
        // New rows inserted after the column was added should have their values
        let value: i64 = db
            .query_one("SELECT new_column FROM alter_test WHERE id = 2", ())
            .unwrap();
        assert_eq!(
            value, 100,
            "New row should have its new_column value persisted"
        );

        // The default expression should work for new inserts
        db.execute("INSERT INTO alter_test (id, name) VALUES (3, 'third')", ())
            .unwrap();
        let value: i64 = db
            .query_one("SELECT new_column FROM alter_test WHERE id = 3", ())
            .unwrap();
        assert_eq!(value, 42, "New insert should use default value");

        db.close().unwrap();
    }
}

/// Test that ALTER TABLE RENAME TO IS persisted after database restart.
/// RENAME TABLE is recorded to WAL and replayed.
#[test]
fn test_rename_table_persistence() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create table and rename it
    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE original_table (id INTEGER PRIMARY KEY, name TEXT)",
            (),
        )
        .unwrap();

        db.execute("INSERT INTO original_table VALUES (1, 'test')", ())
            .unwrap();

        // Rename the table
        db.execute("ALTER TABLE original_table RENAME TO renamed_table", ())
            .unwrap();

        // Verify renamed table works in this session
        let count: i64 = db
            .query_one("SELECT COUNT(*) FROM renamed_table", ())
            .unwrap();
        assert_eq!(count, 1, "Renamed table should have 1 row");

        db.close().unwrap();
    }

    // Session 2: Verify rename was persisted
    {
        let db = Database::open(&dsn).unwrap();

        // The renamed table should exist after restart
        let count: i64 = db
            .query_one("SELECT COUNT(*) FROM renamed_table", ())
            .unwrap();
        assert_eq!(count, 1, "Renamed table should have 1 row after restart");

        // The original table name should not exist
        let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM original_table", ());
        assert!(result.is_err(), "Original table name should not exist");

        db.close().unwrap();
    }
}

/// Test that DEFAULT constraints ARE properly persisted after database restart.
/// FIXED: serialize_schema() and deserialize_schema() now include default_expr.
#[test]
fn test_default_constraint_persistence() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create table with DEFAULT constraint
    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE defaults_test (
                id INTEGER PRIMARY KEY,
                name TEXT NOT NULL,
                status TEXT DEFAULT 'active',
                count INTEGER DEFAULT 100
            )",
            (),
        )
        .unwrap();

        // Insert row without specifying defaults
        db.execute(
            "INSERT INTO defaults_test (id, name) VALUES (1, 'test')",
            (),
        )
        .unwrap();

        // Verify defaults work in this session
        let status: String = db
            .query_one("SELECT status FROM defaults_test WHERE id = 1", ())
            .unwrap();
        assert_eq!(status, "active", "DEFAULT should be applied");

        let count: i64 = db
            .query_one("SELECT count FROM defaults_test WHERE id = 1", ())
            .unwrap();
        assert_eq!(count, 100, "DEFAULT should be applied");

        db.close().unwrap();
    }

    // Session 2: Test if defaults still work after restart
    {
        let db = Database::open(&dsn).unwrap();

        // Try to insert a new row relying on defaults
        // This may fail or insert NULL instead of the default value
        let result = db.execute(
            "INSERT INTO defaults_test (id, name) VALUES (2, 'test2')",
            (),
        );

        if result.is_ok() {
            // Check if the default was actually applied
            let status_result: Result<String, _> =
                db.query_one("SELECT status FROM defaults_test WHERE id = 2", ());

            match status_result {
                Ok(status) => {
                    // BUG: If we get here without 'active', the DEFAULT wasn't persisted
                    if status != "active" {
                        panic!(
                            "BUG: DEFAULT constraint not persisted! Expected 'active', got '{}'",
                            status
                        );
                    }
                }
                Err(_) => {
                    // NULL was inserted instead of default
                    panic!("BUG: DEFAULT constraint not persisted! Got NULL instead of 'active'");
                }
            }
        }

        db.close().unwrap();
    }
}

/// Test that CHECK constraints ARE properly persisted after database restart.
/// FIXED: serialize_schema() and deserialize_schema() now include check_expr.
#[test]
fn test_check_constraint_persistence() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create table with CHECK constraint
    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE check_test (
                id INTEGER PRIMARY KEY,
                age INTEGER CHECK (age >= 0 AND age <= 150),
                score INTEGER CHECK (score BETWEEN 0 AND 100)
            )",
            (),
        )
        .unwrap();

        // Verify CHECK constraint works - valid values should succeed
        db.execute("INSERT INTO check_test VALUES (1, 25, 85)", ())
            .unwrap();

        // Verify CHECK constraint works - invalid values should fail
        let invalid_result = db.execute("INSERT INTO check_test VALUES (2, -5, 50)", ());
        assert!(
            invalid_result.is_err(),
            "CHECK constraint should reject negative age"
        );

        db.close().unwrap();
    }

    // Session 2: Test if CHECK constraints still work after restart
    {
        let db = Database::open(&dsn).unwrap();

        // Try to insert invalid data that should be rejected by CHECK constraint
        let invalid_result = db.execute("INSERT INTO check_test VALUES (3, -10, 50)", ());

        if invalid_result.is_ok() {
            // BUG: CHECK constraint was not persisted!
            panic!(
                "BUG: CHECK constraint not persisted! Invalid age -10 was accepted after restart"
            );
        }

        // Also try invalid score
        let invalid_score = db.execute("INSERT INTO check_test VALUES (4, 25, 200)", ());
        if invalid_score.is_ok() {
            panic!(
                "BUG: CHECK constraint not persisted! Invalid score 200 was accepted after restart"
            );
        }

        db.close().unwrap();
    }
}

/// Test that inline UNIQUE constraints (column-level) ARE properly persisted after database restart.
/// FIXED: ddl.rs now calls record_create_index() after creating indexes for inline UNIQUE constraints.
#[test]
fn test_inline_unique_constraint_persistence() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Session 1: Create table with inline UNIQUE constraint
    {
        let db = Database::open(&dsn).unwrap();

        // Using inline UNIQUE constraint (NOT explicit CREATE UNIQUE INDEX)
        db.execute(
            "CREATE TABLE unique_test (
                id INTEGER PRIMARY KEY,
                email TEXT UNIQUE
            )",
            (),
        )
        .unwrap();

        db.execute("INSERT INTO unique_test VALUES (1, 'test@example.com')", ())
            .unwrap();

        // Verify UNIQUE constraint works in this session
        let dup_result = db.execute("INSERT INTO unique_test VALUES (2, 'test@example.com')", ());
        assert!(
            dup_result.is_err(),
            "UNIQUE constraint should reject duplicate"
        );

        db.close().unwrap();
    }

    // Session 2: Test if UNIQUE constraint still works after restart
    {
        let db = Database::open(&dsn).unwrap();

        // Try to insert duplicate email - should be rejected if UNIQUE is persisted
        let dup_result = db.execute("INSERT INTO unique_test VALUES (3, 'test@example.com')", ());

        if dup_result.is_ok() {
            // BUG: UNIQUE constraint was not persisted!
            panic!("BUG: Inline UNIQUE constraint not persisted! Duplicate 'test@example.com' was accepted after restart");
        }

        db.close().unwrap();
    }
}