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
use tokio::fs;
use turso::{Builder, EncryptionOpts, Error, Value};

#[tokio::test]
async fn test_rows_next() {
    let builder = Builder::new_local(":memory:");
    let db = builder.build().await.unwrap();
    let conn = db.connect().unwrap();
    conn.execute("CREATE TABLE test (x INTEGER)", ())
        .await
        .unwrap();
    conn.execute("INSERT INTO test (x) VALUES (1)", ())
        .await
        .unwrap();
    assert_eq!(conn.last_insert_rowid(), 1);
    conn.execute("INSERT INTO test (x) VALUES (2)", ())
        .await
        .unwrap();
    assert_eq!(conn.last_insert_rowid(), 2);
    conn.execute(
        "INSERT INTO test (x) VALUES (:x)",
        vec![(":x".to_string(), Value::Integer(3))],
    )
    .await
    .unwrap();
    assert_eq!(conn.last_insert_rowid(), 3);
    conn.execute(
        "INSERT INTO test (x) VALUES (@x)",
        vec![("@x".to_string(), Value::Integer(4))],
    )
    .await
    .unwrap();
    assert_eq!(conn.last_insert_rowid(), 4);
    conn.execute(
        "INSERT INTO test (x) VALUES ($x)",
        vec![("$x".to_string(), Value::Integer(5))],
    )
    .await
    .unwrap();
    assert_eq!(conn.last_insert_rowid(), 5);
    let mut res = conn.query("SELECT * FROM test", ()).await.unwrap();
    assert_eq!(
        res.next().await.unwrap().unwrap().get_value(0).unwrap(),
        1.into()
    );
    assert_eq!(
        res.next().await.unwrap().unwrap().get_value(0).unwrap(),
        2.into()
    );
    assert_eq!(
        res.next().await.unwrap().unwrap().get_value(0).unwrap(),
        3.into()
    );
    assert_eq!(
        res.next().await.unwrap().unwrap().get_value(0).unwrap(),
        4.into()
    );
    assert_eq!(
        res.next().await.unwrap().unwrap().get_value(0).unwrap(),
        5.into()
    );
    assert!(res.next().await.unwrap().is_none());
}

#[tokio::test]
async fn test_cacheflush() {
    let builder = Builder::new_local("test.db");
    let db = builder.build().await.unwrap();

    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE IF NOT EXISTS asdf (x INTEGER)", ())
        .await
        .unwrap();

    // Tests if cache flush breaks transaction isolation
    conn.execute("BEGIN", ()).await.unwrap();
    conn.execute("INSERT INTO asdf (x) VALUES (1)", ())
        .await
        .unwrap();
    conn.cacheflush().unwrap();
    conn.execute("ROLLBACK", ()).await.unwrap();

    conn.execute("INSERT INTO asdf (x) VALUES (2)", ())
        .await
        .unwrap();
    conn.execute("INSERT INTO asdf (x) VALUES (3)", ())
        .await
        .unwrap();

    let mut res = conn.query("SELECT * FROM asdf", ()).await.unwrap();

    assert_eq!(
        res.next().await.unwrap().unwrap().get_value(0).unwrap(),
        2.into()
    );
    assert_eq!(
        res.next().await.unwrap().unwrap().get_value(0).unwrap(),
        3.into()
    );

    // Tests if cache flush doesn't break a committed transaction
    conn.execute("BEGIN", ()).await.unwrap();
    conn.execute("INSERT INTO asdf (x) VALUES (1)", ())
        .await
        .unwrap();
    conn.cacheflush().unwrap();
    conn.execute("COMMIT", ()).await.unwrap();

    let mut res = conn
        .query("SELECT * FROM asdf WHERE x = 1", ())
        .await
        .unwrap();

    assert_eq!(
        res.next().await.unwrap().unwrap().get_value(0).unwrap(),
        1.into()
    );

    fs::remove_file("test.db").await.unwrap();
    fs::remove_file("test.db-wal").await.unwrap();
}

#[tokio::test]
async fn test_rows_returned() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    //--- CRUD Operations ---//
    conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, val TEXT)", ())
        .await
        .unwrap();
    let changed = conn
        .execute("INSERT INTO t VALUES (1,'hello')", ())
        .await
        .unwrap();
    let changed1 = conn
        .execute("INSERT INTO t VALUES (2,'hi')", ())
        .await
        .unwrap();
    let changed2 = conn
        .execute("UPDATE t SET val='hi' WHERE id=1", ())
        .await
        .unwrap();
    let changed3 = conn
        .execute("DELETE FROM t WHERE val='hi'", ())
        .await
        .unwrap();
    assert_eq!(changed, 1);
    assert_eq!(changed1, 1);
    assert_eq!(changed2, 1);
    assert_eq!(changed3, 2);

    //--- A more complicated example of insert with a select join subquery ---//
    conn.execute(
        "CREATE TABLE authors ( id INTEGER PRIMARY KEY, name TEXT NOT NULL);
       ",
        (),
    )
    .await
    .unwrap();

    conn.execute(
       "CREATE TABLE books ( id INTEGER PRIMARY KEY, author_id INTEGER NOT NULL REFERENCES authors(id), title TEXT NOT NULL); "
       ,()
   ).await.unwrap();

    conn.execute(
        "CREATE TABLE prize_winners ( book_id INTEGER PRIMARY KEY, author_name TEXT NOT NULL);",
        (),
    )
    .await
    .unwrap();

    conn.execute(
        "INSERT INTO authors (id, name) VALUES (1, 'Alice'), (2, 'Bob');",
        (),
    )
    .await
    .unwrap();

    conn.execute(
       "INSERT INTO books (id, author_id, title) VALUES (1, 1, 'Rust in Action'), (2, 1, 'Async Adventures'), (3, 1, 'Fearless Concurrency'), (4, 1, 'Unsafe Tales'), (5, 1, 'Zero-Cost Futures'), (6, 2, 'Learning SQL');",
       ()
   ).await.unwrap();

    let rows_changed = conn
        .execute(
            "
       INSERT INTO prize_winners (book_id, author_name)
       SELECT b.id, a.name
       FROM   books b
       JOIN   authors a ON a.id = b.author_id
       WHERE  a.id = 1;       -- Alice's five books
       ",
            (),
        )
        .await
        .unwrap();

    assert_eq!(rows_changed, 5);
}

#[tokio::test]
pub async fn test_execute_batch() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();
    conn.execute_batch("CREATE TABLE authors ( id INTEGER PRIMARY KEY, name TEXT NOT NULL);CREATE TABLE books ( id INTEGER PRIMARY KEY, author_id INTEGER NOT NULL REFERENCES authors(id), title TEXT NOT NULL); INSERT INTO authors (id, name) VALUES (1, 'Alice'), (2, 'Bob');")
        .await
        .unwrap();
    let mut rows = conn
        .query("SELECT COUNT(*) FROM authors;", ())
        .await
        .unwrap();
    if let Some(row) = rows.next().await.unwrap() {
        assert_eq!(row.get_value(0).unwrap(), Value::Integer(2));
    }
}

#[tokio::test]
async fn test_query_row_returns_first_row() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE users (id INTEGER, name TEXT)", ())
        .await
        .unwrap();

    conn.execute("INSERT INTO users VALUES (1, 'Frodo')", ())
        .await
        .unwrap();

    let row = conn
        .prepare("SELECT id FROM users WHERE name = ?")
        .await
        .unwrap()
        .query_row(&["Frodo"])
        .await
        .unwrap();

    let id: i64 = row.get(0).unwrap();
    assert_eq!(id, 1);
}

#[tokio::test]
async fn test_query_row_returns_no_rows_error() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE users (id INTEGER, name TEXT)", ())
        .await
        .unwrap();

    let result = conn
        .prepare("SELECT id FROM users WHERE name = ?")
        .await
        .unwrap()
        .query_row(&["Ghost"])
        .await;

    assert!(matches!(result, Err(Error::QueryReturnedNoRows)));
}

#[tokio::test]
async fn test_row_get_column_typed() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE v (n INTEGER, label TEXT)", ())
        .await
        .unwrap();

    conn.execute("INSERT INTO v VALUES (42, 'answer')", ())
        .await
        .unwrap();

    let mut rows = conn.query("SELECT * FROM v", ()).await.unwrap();
    let row = rows.next().await.unwrap().unwrap();

    let n: i64 = row.get(0).unwrap();
    let label: String = row.get(1).unwrap();

    assert_eq!(n, 42);
    assert_eq!(label, "answer");
}

#[tokio::test]
async fn test_row_get_conversion_error() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE t (x TEXT)", ()).await.unwrap();

    conn.execute("INSERT INTO t VALUES (NULL)", ())
        .await
        .unwrap();

    let mut rows = conn.query("SELECT x FROM t", ()).await.unwrap();
    let row = rows.next().await.unwrap().unwrap();

    // Attempt to convert TEXT into integer (should fail)
    let result: Result<u32, _> = row.get(0);
    assert!(matches!(result, Err(Error::ConversionFailure(_))));
}

#[tokio::test]
async fn test_index() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE users (name TEXT PRIMARY KEY, email TEXT)", ())
        .await
        .unwrap();
    conn.execute("CREATE INDEX email_idx ON users(email)", ())
        .await
        .unwrap();
    conn.execute(
        "INSERT INTO users VALUES ('alice', 'a@b.c'), ('bob', 'b@d.e')",
        (),
    )
    .await
    .unwrap();

    let mut rows = conn
        .query("SELECT * FROM users WHERE email = 'a@b.c'", ())
        .await
        .unwrap();
    let row = rows.next().await.unwrap().unwrap();
    assert!(row.get::<String>(0).unwrap() == "alice");
    assert!(row.get::<String>(1).unwrap() == "a@b.c");
    assert!(rows.next().await.unwrap().is_none());

    let mut rows = conn
        .query("SELECT * FROM users WHERE email = 'b@d.e'", ())
        .await
        .unwrap();
    let row = rows.next().await.unwrap().unwrap();
    assert!(row.get::<String>(0).unwrap() == "bob");
    assert!(row.get::<String>(1).unwrap() == "b@d.e");
    assert!(rows.next().await.unwrap().is_none());
}

#[tokio::test]
/// Tests that concurrent statements that error out and rollback can do so without panicking
async fn test_concurrent_unique_constraint_regression() {
    use std::sync::Arc;
    use tokio::sync::Barrier;

    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute(
        "CREATE TABLE users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            email TEXT UNIQUE,
            created_at DATETIME
        )",
        (),
    )
    .await
    .unwrap();

    // Insert initial seed data
    conn.execute(
        "INSERT INTO users (email, created_at) VALUES (:email, :created_at)",
        vec![
            (":email".to_string(), Value::Text("seed@example.com".into())),
            (":created_at".to_string(), Value::Text("whatever".into())),
        ],
    )
    .await
    .unwrap();

    let barrier = Arc::new(Barrier::new(8));
    let mut handles = Vec::new();

    // Spawn 8 concurrent workers
    for _ in 0..8 {
        let conn = db.connect().unwrap();
        let barrier = barrier.clone();

        handles.push(tokio::spawn(async move {
            barrier.wait().await;

            let mut prepared_stmt = conn
                .prepare("INSERT INTO users (email, created_at) VALUES (:email, :created_at)")
                .await
                .unwrap();
            for i in 0..1000 {
                let email = match i % 3 {
                    0 => "seed@example.com",
                    1 => "dup@example.com",
                    2 => "dapper@example.com",
                    _ => panic!("Invalid email index: {i}"),
                };
                let result = prepared_stmt
                    .execute(vec![
                        (":email".to_string(), Value::Text(email.into())),
                        (":created_at".to_string(), Value::Text("whatever".into())),
                    ])
                    .await;
                match result {
                    Ok(_) => (),
                    Err(Error::Constraint(e)) if e.contains("UNIQUE constraint failed") => {}
                    Err(Error::Busy(e)) if e.contains("database is locked") => {}
                    Err(e) => {
                        panic!("Error executing statement: {e:?}");
                    }
                }
            }
        }));
    }

    // Wait for all workers to complete
    for handle in handles {
        handle.await.unwrap();
    }
}

#[tokio::test]
async fn test_statement_query_resets_before_execution() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, value TEXT)", ())
        .await
        .unwrap();

    for i in 0..5 {
        conn.execute(&format!("INSERT INTO t VALUES ({i}, 'value_{i}')"), ())
            .await
            .unwrap();
    }

    let mut stmt = conn
        .prepare("SELECT id, value FROM t ORDER BY id")
        .await
        .unwrap();

    let mut rows = stmt.query(()).await.unwrap();
    let mut count = 0;
    while let Some(row) = rows.next().await.unwrap() {
        let id: i64 = row.get(0).unwrap();
        assert_eq!(id, count);
        count += 1;
    }
    assert_eq!(count, 5);

    let mut rows = stmt.query(()).await.unwrap();
    let mut count = 0;
    while let Some(row) = rows.next().await.unwrap() {
        let id: i64 = row.get(0).unwrap();
        assert_eq!(id, count);
        count += 1;
    }
    // this will return 0 rows if query() does not reset the statement
    assert_eq!(count, 5, "Second query() should return all rows again");
}

#[tokio::test]
async fn test_encryption() {
    let temp_dir = tempfile::tempdir().unwrap();
    let db_file = temp_dir.path().join("test-encrypted.db");
    let db_file = db_file.to_str().unwrap();
    let hexkey = "b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327";
    let wrong_key = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
    let encryption_opts = EncryptionOpts {
        hexkey: hexkey.to_string(),
        cipher: "aegis256".to_string(),
    };

    // 1. Create encrypted database and insert data
    {
        let builder = Builder::new_local(db_file)
            .experimental_encryption(true)
            .with_encryption(encryption_opts.clone());
        let db = builder.build().await.unwrap();
        let conn = db.connect().unwrap();
        conn.execute(
            "CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT);",
            (),
        )
        .await
        .unwrap();
        conn.execute("INSERT INTO test (value) VALUES ('secret_data')", ())
            .await
            .unwrap();
        let mut row_count = 0;
        let mut rows = conn.query("SELECT * FROM test", ()).await.unwrap();
        while let Some(row) = rows.next().await.unwrap() {
            assert_eq!(row.get::<i64>(0).unwrap(), 1);
            assert_eq!(row.get::<String>(1).unwrap(), "secret_data");
            row_count += 1;
        }
        assert_eq!(row_count, 1);

        // Checkpoint to ensure data is written to main db file
        let mut rows = conn
            .query("PRAGMA wal_checkpoint(TRUNCATE)", ())
            .await
            .unwrap();
        while rows.next().await.unwrap().is_some() {}
    }

    // 2. Verify data is encrypted on disk
    let content = std::fs::read(db_file).unwrap();
    assert!(content.len() > 1024);
    assert!(
        !content.windows(11).any(|w| w == b"secret_data"),
        "Plaintext should not appear in encrypted database file"
    );

    // 3. Reopen with correct key and verify data
    {
        let builder = Builder::new_local(db_file)
            .experimental_encryption(true)
            .with_encryption(encryption_opts.clone());
        let db = builder.build().await.unwrap();
        let conn = db.connect().unwrap();

        let mut row_count = 0;
        let mut rows = conn.query("SELECT * FROM test", ()).await.unwrap();
        while let Some(row) = rows.next().await.unwrap() {
            assert_eq!(row.get::<i64>(0).unwrap(), 1);
            assert_eq!(row.get::<String>(1).unwrap(), "secret_data");
            row_count += 1;
        }
        assert_eq!(row_count, 1);
    }

    // 4. Verify opening with wrong key fails
    {
        let wrong_opts = EncryptionOpts {
            hexkey: wrong_key.to_string(),
            cipher: "aegis256".to_string(),
        };
        let builder = Builder::new_local(db_file)
            .experimental_encryption(true)
            .with_encryption(wrong_opts);
        let result = builder.build().await;
        assert!(result.is_err(), "Opening with wrong key should fail");
    }

    // 5. Verify opening without encryption fails
    {
        let builder = Builder::new_local(db_file).experimental_encryption(true);
        let result = builder.build().await;
        assert!(
            result.is_err(),
            "Opening encrypted database without key should fail"
        );
    }
}

#[tokio::test]
/// This results in a panic if the query isn't correctly reset
async fn test_query_without_reset_does_not_panic() {
    let tempfile = tempfile::NamedTempFile::new().unwrap();
    let db = Builder::new_local(tempfile.path().to_str().unwrap())
        .build()
        .await
        .unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, value TEXT)", ())
        .await
        .unwrap();

    for i in 0..10 {
        conn.execute(&format!("INSERT INTO t VALUES ({i}, 'val')"), ())
            .await
            .unwrap();
    }

    let mut stmts: Vec<Option<turso::Statement>> = Vec::new();

    for round in 0..4 {
        for i in 0..30 {
            let id = 100 + round * 100 + i;
            let sql = match i % 4 {
                0 => format!("INSERT INTO t VALUES ({id}, 'new')"),
                1 => "SELECT * FROM t".to_string(),
                2 => format!("UPDATE t SET value = 'upd' WHERE id = {}", i % 10),
                _ => format!("DELETE FROM t WHERE id = {}", 1000 + i),
            };
            if let Ok(s) = conn.prepare(&sql).await {
                stmts.push(Some(s));
            }
        }

        for i in (0..stmts.len()).step_by(7) {
            if let Some(Some(stmt)) = stmts.get_mut(i) {
                if let Ok(mut rows) = stmt.query(()).await {
                    let _ = rows.next().await;
                }
            }
        }

        for i in 0..3 {
            let _ = conn
                .execute(
                    &format!("INSERT INTO t VALUES ({}, 'x')", 2000 + round * 10 + i),
                    (),
                )
                .await;
        }

        for i in (0..stmts.len()).step_by(13) {
            stmts[i] = None;
        }

        for i in (0..stmts.len()).step_by(5) {
            if let Some(Some(stmt)) = stmts.get_mut(i) {
                if let Ok(mut rows) = stmt.query(()).await {
                    let _ = rows.next().await;
                }
            }
        }
    }
}

// Test Transaction.prepare
#[tokio::test]
async fn test_transaction_prepared_statement() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let mut conn = db.connect().unwrap();

    conn.execute("CREATE TABLE users (id INTEGER, name TEXT)", ())
        .await
        .unwrap();

    let tx = conn.transaction().await.unwrap();
    let mut stmt = tx
        .prepare("INSERT INTO users VALUES (?1, ?2)")
        .await
        .unwrap();
    stmt.execute(["1", "Frodo"]).await.unwrap();
    tx.commit().await.unwrap();

    let row = conn
        .prepare("SELECT id FROM users WHERE name = ?")
        .await
        .unwrap()
        .query_row(&["Frodo"])
        .await
        .unwrap();

    let id: i64 = row.get(0).unwrap();
    assert_eq!(id, 1);
}

#[tokio::test]
async fn test_row_get_value_out_of_bounds() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE t (x INTEGER)", ())
        .await
        .unwrap();
    conn.execute("INSERT INTO t VALUES (1)", ()).await.unwrap();

    let mut rows = conn.query("SELECT x FROM t", ()).await.unwrap();
    let row = rows.next().await.unwrap().unwrap();

    // Valid index works
    assert!(row.get_value(0).is_ok());

    // Out of bounds returns error instead of panicking
    let result = row.get_value(999);
    assert!(matches!(result, Err(Error::Misuse(_))));

    // Also test get<T>() for OOB
    let result: Result<i64, _> = row.get(999);
    assert!(matches!(result, Err(Error::Misuse(_))));
}

// Test Connection clone
#[tokio::test]
async fn test_connection_clone() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let mut conn = db.connect().unwrap();

    conn.execute("CREATE TABLE users (id INTEGER, name TEXT)", ())
        .await
        .unwrap();

    let tx = conn.transaction().await.unwrap();
    let mut stmt = tx
        .prepare("INSERT INTO users VALUES (?1, ?2)")
        .await
        .unwrap();
    stmt.execute(["1", "Frodo"]).await.unwrap();
    tx.commit().await.unwrap();

    let conn2 = conn.clone();
    let row = conn2
        .prepare("SELECT id FROM users WHERE name = ?")
        .await
        .unwrap()
        .query_row(&["Frodo"])
        .await
        .unwrap();

    let id: i64 = row.get(0).unwrap();
    assert_eq!(id, 1);
}

#[tokio::test]
async fn test_insert_returning_partial_consume() {
    // Regression test for: INSERT...RETURNING should insert all rows even if
    // only some RETURNING values are consumed before the statement is dropped/reset.
    // This matches the sqlite3 bindings fix in commit e39e60ef1.
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE t (x INTEGER)", ())
        .await
        .unwrap();

    // Use query() to get RETURNING values, but only consume first row
    let mut stmt = conn
        .prepare("INSERT INTO t (x) VALUES (1), (2), (3) RETURNING x")
        .await
        .unwrap();
    let mut rows = stmt.query(()).await.unwrap();

    // Only consume first row
    let first_row = rows.next().await.unwrap().unwrap();
    assert_eq!(first_row.get::<i64>(0).unwrap(), 1);

    // Drop the rows iterator without consuming remaining rows
    drop(rows);
    drop(stmt);

    // All 3 rows should have been inserted despite only consuming 1 RETURNING value
    let mut count_rows = conn.query("SELECT COUNT(*) FROM t", ()).await.unwrap();
    let count: i64 = count_rows.next().await.unwrap().unwrap().get(0).unwrap();
    assert_eq!(
        count, 3,
        "All 3 rows should be inserted even if RETURNING was partially consumed"
    );
}

#[tokio::test]
async fn test_transaction_commit_without_mvcc() {
    // Regression test: COMMIT should work for non-MVCC transactions.
    // The op_auto_commit function must check TransactionState, not just MVCC tx.
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)", ())
        .await
        .unwrap();

    // Begin explicit transaction
    conn.execute("BEGIN IMMEDIATE TRANSACTION", ())
        .await
        .unwrap();

    // Insert data within transaction
    conn.execute("INSERT INTO test (id, value) VALUES (1, 'hello')", ())
        .await
        .unwrap();

    // Commit should succeed
    conn.execute("COMMIT", ())
        .await
        .expect("COMMIT should succeed for non-MVCC transactions");

    // Verify data was committed
    let mut rows = conn
        .query("SELECT value FROM test WHERE id = 1", ())
        .await
        .unwrap();
    let row = rows.next().await.unwrap().unwrap();
    let value: String = row.get(0).unwrap();
    assert_eq!(value, "hello", "Data should be committed");
}

#[tokio::test]
async fn test_transaction_with_insert_returning_then_commit() {
    // Regression test: Combining INSERT...RETURNING (partial consume) with explicit transaction.
    // This tests the interaction between the reset-to-completion fix and transaction commit.
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE t (x INTEGER)", ())
        .await
        .unwrap();

    // Begin transaction
    conn.execute("BEGIN IMMEDIATE TRANSACTION", ())
        .await
        .unwrap();

    // INSERT...RETURNING, only consume first row
    let mut stmt = conn
        .prepare("INSERT INTO t (x) VALUES (1), (2), (3) RETURNING x")
        .await
        .unwrap();
    let mut rows = stmt.query(()).await.unwrap();
    let first = rows.next().await.unwrap().unwrap();
    assert_eq!(first.get::<i64>(0).unwrap(), 1);
    drop(rows);
    drop(stmt);

    // Commit should succeed even after partial RETURNING consumption
    conn.execute("COMMIT", ())
        .await
        .expect("COMMIT should succeed after INSERT...RETURNING");

    // Verify all 3 rows were inserted
    let mut count_rows = conn.query("SELECT COUNT(*) FROM t", ()).await.unwrap();
    let count: i64 = count_rows.next().await.unwrap().unwrap().get(0).unwrap();
    assert_eq!(count, 3, "All rows should be committed");
}

#[tokio::test]
async fn test_prepare_cached_basic() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

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

    // First call should cache the statement
    let mut stmt1 = conn
        .prepare_cached("SELECT * FROM users WHERE id = ?")
        .await
        .unwrap();

    // Insert some data and query
    conn.execute("INSERT INTO users VALUES (1, 'Alice')", ())
        .await
        .unwrap();

    let mut rows = stmt1.query(vec![Value::Integer(1)]).await.unwrap();
    let row = rows.next().await.unwrap().unwrap();
    assert_eq!(row.get::<i64>(0).unwrap(), 1);
    assert_eq!(row.get::<String>(1).unwrap(), "Alice");
    drop(rows);
    drop(stmt1);

    // Second call should use cached statement
    let mut stmt2 = conn
        .prepare_cached("SELECT * FROM users WHERE id = ?")
        .await
        .unwrap();

    let mut rows = stmt2.query(vec![Value::Integer(1)]).await.unwrap();
    let row = rows.next().await.unwrap().unwrap();
    assert_eq!(row.get::<i64>(0).unwrap(), 1);
    assert_eq!(row.get::<String>(1).unwrap(), "Alice");
}

#[tokio::test]
async fn test_prepare_cached_reprepare_on_query_only_change() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE t (id INTEGER)", ())
        .await
        .unwrap();

    let mut stmt = conn
        .prepare_cached("INSERT INTO t VALUES (?)")
        .await
        .unwrap();

    conn.execute("PRAGMA query_only=1", ()).await.unwrap();

    let err = stmt.execute(vec![Value::Integer(1)]).await.unwrap_err();
    assert!(err.to_string().to_ascii_lowercase().contains("query_only"));

    let mut rows = conn.query("SELECT COUNT(*) FROM t", ()).await.unwrap();
    let count: i64 = rows.next().await.unwrap().unwrap().get(0).unwrap();
    assert_eq!(count, 0);
}

#[tokio::test]
async fn test_prepare_cached_batch_insert_delete_pattern() {
    #[derive(Clone)]
    struct Host {
        name: String,
        app: String,
        address: String,
        namespace: String,
        cloud_cluster_name: String,
        allowed_ips: Vec<String>,
        updated_at: std::time::SystemTime,
        deleted: bool,
    }

    fn serialize_allowed_ips(allowed_ips: &[String]) -> String {
        allowed_ips.join(",")
    }

    fn system_time_to_unix_seconds(ts: std::time::SystemTime) -> i64 {
        let duration = ts
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system time should be after unix epoch");
        duration.as_secs() as i64
    }

    async fn insert_hosts(conn: &turso::Connection, hosts: &[Host]) -> Result<(), Error> {
        if hosts.is_empty() {
            return Ok(());
        }

        conn.execute("BEGIN", ()).await?;

        let mut insert_stmt = conn
            .prepare_cached(
                "INSERT INTO hosts (name, app, address, namespace, cloud_cluster_name, allowed_ips, updated_at)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
                 ON CONFLICT(name) DO UPDATE SET
                 app = excluded.app,
                 address = excluded.address,
                 namespace = excluded.namespace,
                 cloud_cluster_name = excluded.cloud_cluster_name,
                 allowed_ips = excluded.allowed_ips,
                 updated_at = excluded.updated_at",
            )
            .await?;
        let mut delete_stmt = conn
            .prepare_cached("DELETE FROM hosts WHERE name = ?1")
            .await?;

        let result = async {
            for host in hosts {
                if host.deleted {
                    delete_stmt.execute([host.name.as_str()]).await?;
                    continue;
                }

                let allowed_ips = serialize_allowed_ips(&host.allowed_ips);
                let updated_at = system_time_to_unix_seconds(host.updated_at);
                insert_stmt
                    .execute((
                        host.name.as_str(),
                        host.app.as_str(),
                        host.address.as_str(),
                        host.namespace.as_str(),
                        host.cloud_cluster_name.as_str(),
                        allowed_ips,
                        updated_at,
                    ))
                    .await?;
            }
            Ok(())
        }
        .await;

        match result {
            Ok(()) => {
                conn.execute("COMMIT", ()).await?;
                Ok(())
            }
            Err(err) => {
                let _ = conn.execute("ROLLBACK", ()).await;
                Err(err)
            }
        }
    }

    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute(
        "CREATE TABLE hosts (
            name TEXT PRIMARY KEY,
            app TEXT,
            address TEXT,
            namespace TEXT,
            cloud_cluster_name TEXT,
            allowed_ips TEXT,
            updated_at INTEGER
        )",
        (),
    )
    .await
    .unwrap();

    let base_time = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
    let hosts = vec![
        Host {
            name: "a".to_string(),
            app: "app_a".to_string(),
            address: "10.0.0.1".to_string(),
            namespace: "ns".to_string(),
            cloud_cluster_name: "cluster".to_string(),
            allowed_ips: vec!["10.0.0.0/24".to_string()],
            updated_at: base_time,
            deleted: false,
        },
        Host {
            name: "b".to_string(),
            app: "app_b".to_string(),
            address: "10.0.0.2".to_string(),
            namespace: "ns".to_string(),
            cloud_cluster_name: "cluster".to_string(),
            allowed_ips: vec!["10.0.1.0/24".to_string()],
            updated_at: base_time,
            deleted: false,
        },
        Host {
            name: "a".to_string(),
            app: "app_a".to_string(),
            address: "10.0.0.1".to_string(),
            namespace: "ns".to_string(),
            cloud_cluster_name: "cluster".to_string(),
            allowed_ips: vec!["10.0.0.0/24".to_string()],
            updated_at: base_time,
            deleted: true,
        },
    ];

    insert_hosts(&conn, &hosts).await.unwrap();

    let mut rows = conn
        .query("SELECT name FROM hosts ORDER BY name", ())
        .await
        .unwrap();
    let first = rows
        .next()
        .await
        .unwrap()
        .unwrap()
        .get::<String>(0)
        .unwrap();
    assert_eq!(first, "b");
    assert!(rows.next().await.unwrap().is_none());
}

#[tokio::test]
async fn test_prepare_cached_multiple_statements() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE t (id INTEGER, value TEXT)", ())
        .await
        .unwrap();

    // Cache multiple different statements
    let queries = vec![
        "SELECT * FROM t WHERE id = ?",
        "SELECT * FROM t WHERE value = ?",
        "INSERT INTO t VALUES (?, ?)",
    ];

    for query in &queries {
        let _ = conn.prepare_cached(*query).await.unwrap();
    }

    // All should be cached and work correctly
    let mut stmt1 = conn.prepare_cached(queries[0]).await.unwrap();
    let mut stmt2 = conn.prepare_cached(queries[1]).await.unwrap();
    let mut stmt3 = conn.prepare_cached(queries[2]).await.unwrap();

    // Insert data
    stmt3
        .execute(vec![Value::Integer(1), Value::Text("test".into())])
        .await
        .unwrap();

    // Query using both cached SELECT statements
    let mut rows = stmt1.query(vec![Value::Integer(1)]).await.unwrap();
    let row = rows.next().await.unwrap().unwrap();
    assert_eq!(row.get::<i64>(0).unwrap(), 1);
    drop(rows);

    let mut rows = stmt2.query(vec![Value::Text("test".into())]).await.unwrap();
    let row = rows.next().await.unwrap().unwrap();
    assert_eq!(row.get::<String>(1).unwrap(), "test");
}

#[tokio::test]
async fn test_prepare_cached_independent_state() {
    // Verify that each cached statement has independent execution state
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE t (id INTEGER)", ())
        .await
        .unwrap();

    for i in 1..=5 {
        conn.execute(&format!("INSERT INTO t VALUES ({i})"), ())
            .await
            .unwrap();
    }

    let query = "SELECT * FROM t ORDER BY id";

    // Get two statements from cache
    let mut stmt1 = conn.prepare_cached(query).await.unwrap();
    let mut stmt2 = conn.prepare_cached(query).await.unwrap();

    // Start iterating with stmt1
    let mut rows1 = stmt1.query(()).await.unwrap();
    let row1 = rows1.next().await.unwrap().unwrap();
    assert_eq!(row1.get::<i64>(0).unwrap(), 1);

    // Start iterating with stmt2 - should have its own state
    let mut rows2 = stmt2.query(()).await.unwrap();
    let row2 = rows2.next().await.unwrap().unwrap();
    assert_eq!(row2.get::<i64>(0).unwrap(), 1);

    // Continue with stmt1 - should be at next row
    let row1 = rows1.next().await.unwrap().unwrap();
    assert_eq!(row1.get::<i64>(0).unwrap(), 2);

    // Continue with stmt2 - should also be at next row (independent state)
    let row2 = rows2.next().await.unwrap().unwrap();
    assert_eq!(row2.get::<i64>(0).unwrap(), 2);
}

#[tokio::test]
async fn test_prepare_cached_with_parameters() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute(
        "CREATE TABLE users (id INTEGER, name TEXT, age INTEGER)",
        (),
    )
    .await
    .unwrap();

    conn.execute("INSERT INTO users VALUES (1, 'Alice', 30)", ())
        .await
        .unwrap();
    conn.execute("INSERT INTO users VALUES (2, 'Bob', 25)", ())
        .await
        .unwrap();
    conn.execute("INSERT INTO users VALUES (3, 'Charlie', 35)", ())
        .await
        .unwrap();

    let query = "SELECT name FROM users WHERE age > ?";

    // Use cached statement with different parameters
    let mut stmt = conn.prepare_cached(query).await.unwrap();

    let mut rows = stmt.query(vec![Value::Integer(25)]).await.unwrap();
    let mut names = Vec::new();
    while let Some(row) = rows.next().await.unwrap() {
        names.push(row.get::<String>(0).unwrap());
    }
    assert_eq!(names.len(), 2);
    assert!(names.contains(&"Alice".to_string()));
    assert!(names.contains(&"Charlie".to_string()));
    drop(rows);

    // Reuse cached statement with different parameter
    let mut rows = stmt.query(vec![Value::Integer(30)]).await.unwrap();
    let mut names = Vec::new();
    while let Some(row) = rows.next().await.unwrap() {
        names.push(row.get::<String>(0).unwrap());
    }
    assert_eq!(names.len(), 1);
    assert_eq!(names[0], "Charlie");
}

#[tokio::test]
async fn test_prepare_cached_stress() {
    // Stress test to ensure cache works correctly under repeated use
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, value TEXT)", ())
        .await
        .unwrap();

    let insert_query = "INSERT INTO t (id, value) VALUES (?, ?)";
    let select_query = "SELECT value FROM t WHERE id = ?";

    // Insert many rows using cached statement
    for i in 0..100 {
        let mut stmt = conn.prepare_cached(insert_query).await.unwrap();
        stmt.execute(vec![Value::Integer(i), Value::Text(format!("value_{i}"))])
            .await
            .unwrap();
    }

    // Query many times using cached statement
    for i in 0..100 {
        let mut stmt = conn.prepare_cached(select_query).await.unwrap();
        let mut rows = stmt.query(vec![Value::Integer(i)]).await.unwrap();
        let row = rows.next().await.unwrap().unwrap();
        assert_eq!(row.get::<String>(0).unwrap(), format!("value_{i}"));
    }
}

#[tokio::test]
async fn test_prepare_vs_prepare_cached_equivalence() {
    // Verify that prepare_cached produces same results as prepare
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute("CREATE TABLE t (x INTEGER, y TEXT)", ())
        .await
        .unwrap();

    conn.execute("INSERT INTO t VALUES (1, 'a'), (2, 'b'), (3, 'c')", ())
        .await
        .unwrap();

    let query = "SELECT * FROM t ORDER BY x";

    // Results from prepare
    let mut stmt1 = conn.prepare(query).await.unwrap();
    let mut rows1 = stmt1.query(()).await.unwrap();
    let mut results1 = Vec::new();
    while let Some(row) = rows1.next().await.unwrap() {
        results1.push((row.get::<i64>(0).unwrap(), row.get::<String>(1).unwrap()));
    }

    // Results from prepare_cached
    let mut stmt2 = conn.prepare_cached(query).await.unwrap();
    let mut rows2 = stmt2.query(()).await.unwrap();
    let mut results2 = Vec::new();
    while let Some(row) = rows2.next().await.unwrap() {
        results2.push((row.get::<i64>(0).unwrap(), row.get::<String>(1).unwrap()));
    }

    // Should produce identical results
    assert_eq!(results1, results2);
    assert_eq!(
        results1,
        vec![
            (1, "a".to_string()),
            (2, "b".to_string()),
            (3, "c".to_string()),
        ]
    );
}

/// This will fail if self.once is not reset in ProgramState::reset.
#[tokio::test]
async fn test_once_not_cleared_on_reset_with_coroutine() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    // This query generates bytecode with Once inside a coroutine:
    // The outer FROM-clause subquery creates a coroutine, and the inner
    // scalar subquery (SELECT 1) uses Once to evaluate only once per execution.
    let mut stmt = conn
        .prepare("SELECT * FROM (SELECT (SELECT 1))")
        .await
        .unwrap();

    let mut rows = stmt.query(()).await.unwrap();
    let row = rows.next().await.unwrap().unwrap();
    let value: i64 = row.get(0).unwrap();
    assert_eq!(value, 1);
    assert!(rows.next().await.unwrap().is_none());
    drop(rows);

    stmt.reset().unwrap();

    let mut rows = stmt.query(()).await.unwrap();
    let row = rows.next().await.unwrap().unwrap();

    assert_eq!(
        row.get_value(0).unwrap(),
        Value::Integer(1),
        "Second execution should return 1, not Null. Bug: state.once not cleared in reset()"
    );
}

#[tokio::test]
async fn test_strict_tables() {
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    // Create a STRICT table
    conn.execute(
        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT) STRICT",
        (),
    )
    .await
    .unwrap();

    // Insert valid data
    conn.execute("INSERT INTO users VALUES (1, 'Alice')", ())
        .await
        .unwrap();

    // Query the data
    let mut rows = conn.query("SELECT id, name FROM users", ()).await.unwrap();
    let row = rows.next().await.unwrap().unwrap();
    assert_eq!(row.get::<i64>(0).unwrap(), 1);
    assert_eq!(row.get::<String>(1).unwrap(), "Alice");
}

// Helper to collect all integer values from a single-column query.
async fn collect_ids(conn: &turso::Connection, sql: &str) -> Vec<i64> {
    let mut rows = conn.query(sql, ()).await.unwrap();
    let mut ids = Vec::new();
    while let Some(row) = rows.next().await.unwrap() {
        let id: i64 = row.get(0).unwrap();
        ids.push(id);
    }
    ids
}

#[tokio::test]
async fn test_check_on_conflict_fail() {
    // FAIL: error on the violating statement, transaction stays active.
    // Prior inserts within the transaction are preserved and can be committed.
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute(
        "CREATE TABLE t(id INTEGER PRIMARY KEY, value INTEGER CHECK(value > 0))",
        (),
    )
    .await
    .unwrap();
    conn.execute("BEGIN", ()).await.unwrap();
    conn.execute("INSERT INTO t VALUES(1, 10)", ())
        .await
        .unwrap();

    // This should fail but keep the transaction active
    let err = conn
        .execute("INSERT OR FAIL INTO t VALUES(2, -5)", ())
        .await;
    assert!(
        err.is_err(),
        "INSERT OR FAIL should error on CHECK violation"
    );

    // Transaction is still active — commit it
    conn.execute("COMMIT", ()).await.unwrap();

    // Row 1 should have survived
    let ids = collect_ids(&conn, "SELECT id FROM t ORDER BY id").await;
    assert_eq!(ids, vec![1]);
}

#[tokio::test]
async fn test_check_on_conflict_abort() {
    // ABORT (default): error on the violating statement, transaction stays active.
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute(
        "CREATE TABLE t(id INTEGER PRIMARY KEY, value INTEGER CHECK(value > 0))",
        (),
    )
    .await
    .unwrap();
    conn.execute("BEGIN", ()).await.unwrap();
    conn.execute("INSERT INTO t VALUES(1, 10)", ())
        .await
        .unwrap();

    let err = conn
        .execute("INSERT OR ABORT INTO t VALUES(2, -5)", ())
        .await;
    assert!(
        err.is_err(),
        "INSERT OR ABORT should error on CHECK violation"
    );

    conn.execute("COMMIT", ()).await.unwrap();

    let ids = collect_ids(&conn, "SELECT id FROM t ORDER BY id").await;
    assert_eq!(ids, vec![1]);
}

#[tokio::test]
async fn test_check_on_conflict_rollback() {
    // ROLLBACK: rolls back the entire transaction.
    // Prior inserts within the transaction are lost, but committed rows survive.
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute(
        "CREATE TABLE t(id INTEGER PRIMARY KEY, value INTEGER CHECK(value > 0))",
        (),
    )
    .await
    .unwrap();
    // Commit row 1 outside the transaction
    conn.execute("INSERT INTO t VALUES(1, 10)", ())
        .await
        .unwrap();

    conn.execute("BEGIN", ()).await.unwrap();
    conn.execute("INSERT INTO t VALUES(2, 20)", ())
        .await
        .unwrap();

    // This should fail AND roll back the transaction
    let err = conn
        .execute("INSERT OR ROLLBACK INTO t VALUES(3, -5)", ())
        .await;
    assert!(
        err.is_err(),
        "INSERT OR ROLLBACK should error on CHECK violation"
    );

    // Transaction was rolled back — row 2 is lost, row 1 survives
    let ids = collect_ids(&conn, "SELECT id FROM t ORDER BY id").await;
    assert_eq!(ids, vec![1]);
}

#[tokio::test]
async fn test_check_on_conflict_replace() {
    // REPLACE: for CHECK constraints, behaves like ABORT.
    // Error, transaction stays active.
    let db = Builder::new_local(":memory:").build().await.unwrap();
    let conn = db.connect().unwrap();

    conn.execute(
        "CREATE TABLE t(id INTEGER PRIMARY KEY, value INTEGER CHECK(value > 0))",
        (),
    )
    .await
    .unwrap();
    conn.execute("BEGIN", ()).await.unwrap();
    conn.execute("INSERT INTO t VALUES(1, 10)", ())
        .await
        .unwrap();

    let err = conn
        .execute("INSERT OR REPLACE INTO t VALUES(1, -5)", ())
        .await;
    assert!(
        err.is_err(),
        "INSERT OR REPLACE should error on CHECK violation"
    );

    conn.execute("COMMIT", ()).await.unwrap();

    let ids = collect_ids(&conn, "SELECT id FROM t ORDER BY id").await;
    assert_eq!(ids, vec![1]);
}

use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tempfile::tempdir;
use tokio::sync::Barrier;

#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
async fn test_lost_updates() {
    let (db, _dir) = setup_mvcc_db(
        "CREATE TABLE counter(id INTEGER PRIMARY KEY, val INTEGER);
         INSERT INTO counter VALUES(1, 0);",
    )
    .await;

    let num_workers: usize = 16;
    let rounds: i64 = 100;
    let total_committed = Arc::new(AtomicI64::new(0));

    for _round in 0..rounds {
        let barrier = Arc::new(Barrier::new(num_workers));
        let mut handles = Vec::new();

        for _ in 0..num_workers {
            let conn = db.connect().unwrap();
            let barrier = barrier.clone();
            let total_committed = total_committed.clone();
            handles.push(tokio::spawn(async move {
                barrier.wait().await;
                if conn.execute("BEGIN CONCURRENT", ()).await.is_err() {
                    return;
                }
                if conn
                    .execute("UPDATE counter SET val = val + 1 WHERE id = 1", ())
                    .await
                    .is_err()
                {
                    let _ = conn.execute("ROLLBACK", ()).await;
                    return;
                }
                match conn.execute("COMMIT", ()).await {
                    Ok(_) => {
                        total_committed.fetch_add(1, Ordering::Relaxed);
                    }
                    Err(_) => {
                        let _ = conn.execute("ROLLBACK", ()).await;
                    }
                }
            }));
        }
        for handle in handles {
            handle.await.unwrap();
        }
    }

    let conn = db.connect().unwrap();
    let val = query_i64(&conn, "SELECT val FROM counter WHERE id = 1").await;
    let committed = total_committed.load(Ordering::Relaxed);
    assert_eq!(
        val, committed,
        "Lost updates! counter={val} but {committed} transactions committed successfully"
    );
}

/// Helper: create MVCC-enabled file-backed database with given schema
async fn setup_mvcc_db(schema: &str) -> (turso::Database, tempfile::TempDir) {
    setup_mvcc_db_with_options(schema, false).await
}

/// Helper: create MVCC-enabled file-backed database with options
async fn setup_mvcc_db_with_options(
    schema: &str,
    triggers: bool,
) -> (turso::Database, tempfile::TempDir) {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let mut builder = Builder::new_local(db_path.to_str().unwrap());
    if triggers {
        builder = builder.experimental_triggers(true);
    }
    let db = builder.build().await.unwrap();
    let conn = db.connect().unwrap();
    // PRAGMA journal_mode returns a row, so use query() to consume it
    let mut rows = conn
        .query("PRAGMA journal_mode = 'mvcc'", ())
        .await
        .unwrap();
    while let Ok(Some(_)) = rows.next().await {}
    drop(rows);
    if !schema.is_empty() {
        conn.execute_batch(schema).await.unwrap();
    }
    (db, dir)
}

/// Helper: query a single i64 value
async fn query_i64(conn: &turso::Connection, sql: &str) -> i64 {
    let mut rows = conn.query(sql, ()).await.unwrap();
    let row = rows.next().await.unwrap().unwrap();
    row.get::<i64>(0).unwrap()
}

#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
#[ignore = "FIXME: This test hangs on main"]
async fn test_deadlock_join_during_writes() {
    let (db, _dir) = setup_mvcc_db(
        "CREATE TABLE orders(id INTEGER PRIMARY KEY, customer_id INTEGER, amount INTEGER);
         CREATE TABLE customers(id INTEGER PRIMARY KEY, name TEXT);
         INSERT INTO customers VALUES(1, 'alice');
         INSERT INTO customers VALUES(2, 'bob');
         INSERT INTO customers VALUES(3, 'charlie');",
    )
    .await;

    let done = Arc::new(AtomicBool::new(false));
    let mut handles = vec![];

    // Writers: insert orders for various customers
    for w in 0..4 {
        let db = db.clone();
        let done = done.clone();
        handles.push(tokio::spawn(async move {
            let conn = db.connect().unwrap();
            let mut i = 0u64;
            while !done.load(Ordering::Relaxed) {
                let id = (w as u64) * 100000 + i;
                let cust = (i % 3) + 1;
                let _ = conn.execute("BEGIN CONCURRENT", ()).await;
                let _ = conn
                    .execute(
                        &format!("INSERT INTO orders VALUES({}, {}, {})", id, cust, 10),
                        (),
                    )
                    .await;
                let _ = conn.execute("COMMIT", ()).await;
                i += 1;
            }
        }));
    }

    // Readers: do JOINs (THIS IS WHAT TRIGGERS THE HANG)
    for _ in 0..4 {
        let db = db.clone();
        let done = done.clone();
        handles.push(tokio::spawn(async move {
            let conn = db.connect().unwrap();
            while !done.load(Ordering::Relaxed) {
                let _ = conn.execute("BEGIN CONCURRENT", ()).await;
                let _orphans = match conn
                    .query(
                        "SELECT COUNT(*) FROM orders o LEFT JOIN customers c ON o.customer_id = c.id WHERE c.id IS NULL",
                        (),
                    )
                    .await
                {
                    Ok(mut rows) => match rows.next().await {
                        Ok(Some(row)) => row.get::<i64>(0).unwrap_or(0),
                        _ => 0,
                    },
                    Err(_) => 0,
                };
                let _ = conn.execute("COMMIT", ()).await;
            }
        }));
    }

    // If this test hangs here, the bug is confirmed.
    tokio::time::sleep(Duration::from_secs(3)).await;
    done.store(true, Ordering::Relaxed);
    for handle in handles {
        // This await will never return if threads are deadlocked
        handle.await.unwrap();
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
async fn test_snapshot_isolation_violation() {
    let (db, _dir) = setup_mvcc_db("CREATE TABLE t(id INTEGER PRIMARY KEY, val INTEGER)").await;

    let done = Arc::new(AtomicBool::new(false));
    let violation_found = Arc::new(AtomicBool::new(false));
    let mut handles = Vec::new();

    // 4 writers: continuously insert batches of 5 rows
    for w in 0..4i64 {
        let conn = db.connect().unwrap();
        let done = done.clone();
        handles.push(tokio::spawn(async move {
            let mut i = 0i64;
            while !done.load(Ordering::Relaxed) {
                if conn.execute("BEGIN CONCURRENT", ()).await.is_err() {
                    continue;
                }
                let mut ok = true;
                for j in 0..5i64 {
                    let id = w * 100_000 + i * 5 + j;
                    if conn
                        .execute(&format!("INSERT INTO t VALUES({id}, {id})"), ())
                        .await
                        .is_err()
                    {
                        ok = false;
                        break;
                    }
                }
                if ok {
                    if conn.execute("COMMIT", ()).await.is_err() {
                        let _ = conn.execute("ROLLBACK", ()).await;
                    }
                } else {
                    let _ = conn.execute("ROLLBACK", ()).await;
                }
                i += 1;
            }
        }));
    }

    // 4 readers: open snapshot, read COUNT(*) twice, assert they match
    for _ in 0..4 {
        let conn = db.connect().unwrap();
        let done = done.clone();
        let violation_found = violation_found.clone();
        handles.push(tokio::spawn(async move {
            while !done.load(Ordering::Relaxed) {
                if conn.execute("BEGIN CONCURRENT", ()).await.is_err() {
                    continue;
                }
                let count1 = query_i64(&conn, "SELECT COUNT(*) FROM t").await;
                tokio::task::yield_now().await; // Let writers commit between reads
                let count2 = query_i64(&conn, "SELECT COUNT(*) FROM t").await;
                let _ = conn.execute("COMMIT", ()).await;
                if count1 != count2 {
                    violation_found.store(true, Ordering::Relaxed);
                    eprintln!(
                        "VIOLATION: COUNT changed {} -> {} within same txn (delta={})",
                        count1,
                        count2,
                        count2 - count1
                    );
                }
            }
        }));
    }

    tokio::time::sleep(Duration::from_secs(3)).await;
    done.store(true, Ordering::Relaxed);
    for handle in handles {
        let _ = handle.await;
    }

    assert!(
        !violation_found.load(Ordering::Relaxed),
        "Snapshot isolation violated: COUNT(*) changed within a single BEGIN CONCURRENT txn"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
async fn test_ghost_commits() {
    for iteration in 0..500 {
        if iteration % 100 == 0 {
            eprintln!("test_ghost_commits: Iteration {iteration}");
        }
        let (db, _dir) = setup_mvcc_db("CREATE TABLE t(id INTEGER PRIMARY KEY, val INTEGER)").await;

        let num_workers: usize = 8;
        let ops_per_worker: i64 = 100;
        let barrier = Arc::new(Barrier::new(num_workers));
        let mut handles = Vec::new();

        for worker_id in 0..num_workers as i64 {
            let conn = db.connect().unwrap();
            let barrier = barrier.clone();
            handles.push(tokio::spawn(async move {
                barrier.wait().await;
                let mut successes = 0i64;
                let mut errors = 0i64;
                for i in 0..ops_per_worker {
                    let id = worker_id * 10_000 + i;
                    // Autocommit INSERT (no explicit BEGIN/COMMIT)
                    match conn
                        .execute(&format!("INSERT INTO t VALUES({id}, {i})"), ())
                        .await
                    {
                        Ok(_) => successes += 1,
                        Err(turso::Error::Busy(_) | turso::Error::BusySnapshot(_)) => errors += 1, // Busy("database is locked")
                        Err(e) => panic!("unexpected error: {e:?}"),
                    }
                }
                (successes, errors)
            }));
        }

        let mut total_successes = 0i64;
        let mut total_errors = 0i64;
        for handle in handles {
            let (s, e) = handle.await.unwrap();
            total_successes += s;
            total_errors += e;
        }

        let conn = db.connect().unwrap();
        let actual_rows = query_i64(&conn, "SELECT COUNT(*) FROM t").await;
        if iteration % 100 == 0 {
            eprintln!("test_ghost_commits: Iteration {iteration}, actual_rows={actual_rows}, total_successes={total_successes}, total_errors={total_errors}");
        }
        assert_eq!(
            actual_rows,
            total_successes,
            "Ghost commits! {actual_rows} rows in DB but only {total_successes} reported as Ok ({total_errors} errors). \
             {} inserts committed despite returning Busy.",
            total_successes - actual_rows,
        );
    }
}

/// AUTOINCREMENT is not supported in MVCC mode. Verify that CREATE TABLE
/// with AUTOINCREMENT fails with a clear error message.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_autoincrement_blocked_in_mvcc() {
    let (db, _dir) = setup_mvcc_db("").await;
    let conn = db.connect().unwrap();

    // CREATE TABLE with AUTOINCREMENT should fail
    let result = conn
        .execute(
            "CREATE TABLE t(a INTEGER PRIMARY KEY AUTOINCREMENT, b TEXT)",
            (),
        )
        .await;
    assert!(
        result.is_err(),
        "CREATE TABLE with AUTOINCREMENT should fail in MVCC mode"
    );
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("AUTOINCREMENT is not supported in MVCC mode"),
        "unexpected error: {err}"
    );

    // Regular tables without AUTOINCREMENT should still work
    conn.execute("CREATE TABLE t(a INTEGER PRIMARY KEY, b TEXT)", ())
        .await
        .unwrap();
    conn.execute("INSERT INTO t VALUES (1, 'hello')", ())
        .await
        .unwrap();
    let count = query_i64(&conn, "SELECT COUNT(*) FROM t").await;
    assert_eq!(count, 1);
}