turso_sdk_kit 0.7.1

Low-level C ABI for building Turso language bindings. For Rust applications, use the `turso` crate instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
use std::{
    collections::HashMap,
    ffi::CString,
    fmt::Display,
    ops::Deref,
    sync::{
        atomic::{AtomicBool, AtomicUsize, Ordering},
        Arc, Mutex, Once, RwLock, Weak,
    },
    task::Waker,
    time::Duration,
};

use tracing::level_filters::LevelFilter;
use tracing_subscriber::{
    fmt::{self, format::Writer},
    layer::{Context, SubscriberExt},
    util::SubscriberInitExt,
    EnvFilter, Layer,
};
use turso_core::{
    storage::database::DatabaseFile, types::AsValueRef, Connection, Database, DatabaseOpts,
    DatabaseStorage, EncryptionKey, IOResult, LimboError, OpenDbAsyncState, OpenFlags, QueryMode,
    Statement, StepResult, IO,
};

use crate::{
    assert_send, assert_sync,
    capi::{self, c},
    ConcurrentGuard,
};

assert_send!(TursoDatabase, TursoConnection, TursoStatement);
assert_sync!(TursoDatabase);

#[derive(Default)]
pub struct SyncBusyGate {
    active: AtomicBool,
}

impl SyncBusyGate {
    pub fn set_active(&self, active: bool) {
        self.active.store(active, Ordering::Release);
    }

    pub fn is_active(&self) -> bool {
        self.active.load(Ordering::Acquire)
    }
}

pub struct SyncBusyGuard {
    gate: Arc<SyncBusyGate>,
}

impl SyncBusyGuard {
    pub fn new(gate: Arc<SyncBusyGate>) -> Self {
        gate.set_active(true);
        Self { gate }
    }
}

impl Drop for SyncBusyGuard {
    fn drop(&mut self) {
        self.gate.set_active(false);
    }
}

pub use turso_core::types::FromValue;
pub use turso_ext::{
    AggCtx, ContextDestructor, FinalizeFunction, InitAggFunction, ResultCode, ScalarFunction,
    StepFunction, Value as ExtensionValue, ValueDestructor,
};
pub type EncryptionOpts = turso_core::EncryptionOpts;
pub type Value = turso_core::Value;
pub type ValueRef<'a> = turso_core::types::ValueRef<'a>;
pub type Text = turso_core::types::Text;
pub type TextRef<'a> = turso_core::types::TextRef<'a>;
pub type Numeric = turso_core::Numeric;
pub type NonNan = turso_core::NonNan;

pub struct TursoLog<'a> {
    pub message: &'a str,
    pub target: &'a str,
    pub file: &'a str,
    pub timestamp: u64,
    pub line: usize,
    pub level: &'a str,
}

type Logger = dyn Fn(TursoLog) + Send + Sync + 'static;
pub struct TursoSetupConfig {
    pub logger: Option<Box<Logger>>,
    pub log_level: Option<String>,
}

fn logger_wrap(log: TursoLog<'_>, logger: unsafe extern "C" fn(*const c::turso_log_t)) {
    let Ok(message_cstr) = std::ffi::CString::new(log.message) else {
        return;
    };
    let Ok(target_cstr) = std::ffi::CString::new(log.target) else {
        return;
    };
    let Ok(file_cstr) = std::ffi::CString::new(log.file) else {
        return;
    };
    unsafe {
        logger(&c::turso_log_t {
            message: message_cstr.as_ptr(),
            target: target_cstr.as_ptr(),
            file: file_cstr.as_ptr(),
            timestamp: log.timestamp,
            line: log.line,
            level: match log.level {
                "TRACE" => capi::c::turso_tracing_level_t::TURSO_TRACING_LEVEL_TRACE,
                "DEBUG" => capi::c::turso_tracing_level_t::TURSO_TRACING_LEVEL_DEBUG,
                "INFO" => capi::c::turso_tracing_level_t::TURSO_TRACING_LEVEL_INFO,
                "WARN" => capi::c::turso_tracing_level_t::TURSO_TRACING_LEVEL_WARN,
                _ => capi::c::turso_tracing_level_t::TURSO_TRACING_LEVEL_ERROR,
            },
        })
    };
}

impl TursoSetupConfig {
    /// helper method to restore [TursoSetupConfig] instance from C representation
    /// this method is used in the capi wrappers
    ///
    /// # Safety
    /// [c::turso_config_t::log_level] field must be valid C-string pointer or null
    pub unsafe fn from_capi(config: *const c::turso_config_t) -> Result<Self, TursoError> {
        if config.is_null() {
            return Err(TursoError::Misuse(
                "config pointer must be not null".to_string(),
            ));
        }
        let config = *config;
        Ok(Self {
            log_level: if !config.log_level.is_null() {
                Some(str_from_c_str(config.log_level)?.to_string())
            } else {
                None
            },
            logger: if let Some(logger) = config.logger {
                Some(Box::new(move |log| logger_wrap(log, logger)))
            } else {
                None
            },
        })
    }
}

#[derive(Clone)]
pub struct TursoDatabaseConfig {
    /// path to the database file or ":memory:" for in-memory connection
    pub path: String,

    /// comma-separated list of experimental features to enable
    /// this field is intentionally just a string in order to make enablement of experimental features as flexible as possible
    pub experimental_features: Option<String>,

    /// if true, library methods will return Io status code and delegate Io loop to the caller
    /// if false, library will spin IO itself in case of Io status code and never return it to the caller
    pub async_io: bool,

    /// optional encryption parameters for local data encryption
    /// as encryption is experimental - [Self::experimental_features] must have "encryption" in the list
    pub encryption: Option<EncryptionOpts>,

    /// optional VFS parameter explicitly specifying FS backend for the database.
    /// Available options are:
    /// - "memory": in-memory backend
    /// - "syscall": generic syscall backend
    /// - "io_uring": IO uring (supported only on Linux)
    pub vfs: Option<String>,

    /// optional custom IO provided by the caller
    pub io: Option<Arc<dyn IO>>,

    /// optional custom DatabaseStorage provided by the caller
    /// if provided, caller must guarantee that IO used by the TursoDatabase will be consistent with underlying DatabaseStorage IO
    pub db_file: Option<Arc<dyn DatabaseStorage>>,
}

impl TursoDatabaseConfig {
    /// Build the typed [`turso_core::DatabaseOpts`] from the comma-separated
    /// [`Self::experimental_features`] string. The feature-name tokens are the
    /// SDK/CLI-facing names; unknown names are ignored and `"strict"` is a
    /// no-op (strict tables are always enabled). This keeps the
    /// string -> typed-options translation in the SDK layer where the string
    /// representation lives, instead of in `turso_core`.
    pub fn database_opts(&self) -> DatabaseOpts {
        let mut opts = DatabaseOpts::new();
        let Some(experimental_features) = &self.experimental_features else {
            return opts;
        };
        for feature in experimental_features.split(',').map(|s| s.trim()) {
            opts = match feature {
                "views" => opts.with_views(true),
                "index_method" => opts.with_index_method(true),
                "custom_types" => opts.with_custom_types(true),
                "autovacuum" => opts.with_autovacuum(true),
                "vacuum" => opts.with_vacuum(true),
                "encryption" => opts.with_encryption(true),
                "attach" => opts.with_attach(true),
                "generated_columns" => opts.with_generated_columns(true),
                "multiprocess_wal" => opts.with_multiprocess_wal(true),
                "without_rowid" => opts.with_without_rowid(true),
                "mvcc_passive_checkpoint" => opts.with_experimental_mvcc_passive_checkpoint(true),
                // "strict" is always enabled, kept for backwards compatibility
                _ => opts,
            };
        }
        opts
    }
}

pub fn turso_slice_from_bytes(bytes: &[u8]) -> capi::c::turso_slice_ref_t {
    capi::c::turso_slice_ref_t {
        ptr: bytes.as_ptr() as *const std::ffi::c_void,
        len: bytes.len(),
    }
}

pub fn turso_slice_null() -> capi::c::turso_slice_ref_t {
    capi::c::turso_slice_ref_t {
        ptr: std::ptr::null(),
        len: 0,
    }
}

/// # Safety
/// ptr must be valid C-string pointer or null
pub unsafe fn str_from_c_str<'a>(ptr: *const std::ffi::c_char) -> Result<&'a str, TursoError> {
    if ptr.is_null() {
        return Err(TursoError::Misuse(
            "expected zero terminated c string, got null pointer".to_string(),
        ));
    }
    let c_str = std::ffi::CStr::from_ptr(ptr);
    match c_str.to_str() {
        Ok(s) => Ok(s),
        Err(err) => Err(TursoError::Misuse(format!(
            "expected zero terminated c-string representing utf-8 value: {err}"
        ))),
    }
}

/// # Safety
/// memory range [ptr..ptr + len) must be valid
pub unsafe fn str_from_slice<'a>(
    ptr: *const std::ffi::c_char,
    len: usize,
) -> Result<&'a str, TursoError> {
    let slice = bytes_from_slice(ptr, len)?;
    match std::str::from_utf8(slice) {
        Ok(s) => Ok(s),
        Err(err) => Err(TursoError::Misuse(format!(
            "expected string slice representing utf-8 value: {err}"
        ))),
    }
}

/// # Safety
/// memory range [ptr..ptr + len) must be valid
pub unsafe fn bytes_from_slice<'a>(
    ptr: *const std::ffi::c_char,
    len: usize,
) -> Result<&'a [u8], TursoError> {
    if len == 0 {
        return Ok(&[]);
    }
    if ptr.is_null() {
        return Err(TursoError::Misuse(
            "expected slice, got null pointer".to_string(),
        ));
    }
    Ok(std::slice::from_raw_parts(ptr as *const u8, len))
}

/// SAFETY: slice must points to the valid memory
pub fn bytes_from_turso_slice<'a>(
    slice: capi::c::turso_slice_ref_t,
) -> Result<&'a [u8], TursoError> {
    if slice.ptr.is_null() {
        return Err(TursoError::Misuse(
            "expected slice representing utf-8 value, got null".to_string(),
        ));
    }
    Ok(unsafe { std::slice::from_raw_parts(slice.ptr as *const u8, slice.len) })
}

/// SAFETY: slice must points to the valid memory
pub fn str_from_turso_slice<'a>(slice: capi::c::turso_slice_ref_t) -> Result<&'a str, TursoError> {
    if slice.ptr.is_null() {
        return Err(TursoError::Misuse(
            "expected slice representing utf-8 value, got null".to_string(),
        ));
    }
    let s = unsafe { std::slice::from_raw_parts(slice.ptr as *const u8, slice.len) };
    match std::str::from_utf8(s) {
        Ok(s) => Ok(s),
        Err(err) => Err(TursoError::Misuse(format!(
            "expected slice representing utf-8 value: {err}"
        ))),
    }
}

impl TursoDatabaseConfig {
    /// helper method to restore [TursoSetupConfig] instance from C representation
    /// this method is used in the capi wrappers
    ///
    /// # Safety
    /// [c::turso_database_config_t::path] field must be valid C-string pointer
    /// [c::turso_database_config_t::experimental_features] field must be valid C-string pointer or null
    pub unsafe fn from_capi(config: *const c::turso_database_config_t) -> Result<Self, TursoError> {
        if config.is_null() {
            return Err(TursoError::Misuse(
                "config pointer must be not null".to_string(),
            ));
        }
        let config = *config;
        let encryption_cipher = if !config.encryption_cipher.is_null() {
            Some(str_from_c_str(config.encryption_cipher)?.to_string())
        } else {
            None
        };
        let encryption_hexkey = if !config.encryption_hexkey.is_null() {
            Some(str_from_c_str(config.encryption_hexkey)?.to_string())
        } else {
            None
        };
        if encryption_cipher.is_some() != encryption_hexkey.is_some() {
            return Err(TursoError::Misuse(
                "either both encryption cipher and key must be set or no".to_string(),
            ));
        }
        Ok(Self {
            path: str_from_c_str(config.path)?.to_string(),
            experimental_features: if !config.experimental_features.is_null() {
                Some(str_from_c_str(config.experimental_features)?.to_string())
            } else {
                None
            },
            async_io: config.async_io != 0,
            encryption: encryption_cipher.map(|encryption_cipher| EncryptionOpts {
                cipher: encryption_cipher,
                hexkey: encryption_hexkey.unwrap(),
            }),
            vfs: if !config.vfs.is_null() {
                Some(str_from_c_str(config.vfs)?.to_string())
            } else {
                None
            },
            io: None,
            db_file: None,
        })
    }
}

pub struct TursoDatabase {
    config: TursoDatabaseConfig,
    open_state: Mutex<TursoDatabaseOpenState>,
    db: Arc<Mutex<Option<Arc<Database>>>>,
    io: Mutex<Option<Arc<dyn turso_core::IO>>>,
}

/// Phase tracking for async TursoDatabase opening
#[derive(Default, Clone, Copy)]
pub enum TursoDatabaseOpenPhase {
    #[default]
    Init,
    Opening,
    Done,
}

/// State machine for async TursoDatabase opening
pub struct TursoDatabaseOpenState {
    phase: TursoDatabaseOpenPhase,
    io: Option<Arc<dyn IO>>,
    db_file: Option<Arc<dyn DatabaseStorage>>,
    opts: Option<DatabaseOpts>,
    open_flags: OpenFlags,
    open_db_state: OpenDbAsyncState,
}

impl Default for TursoDatabaseOpenState {
    fn default() -> Self {
        Self::new()
    }
}

impl TursoDatabaseOpenState {
    pub fn new() -> Self {
        Self {
            phase: TursoDatabaseOpenPhase::Init,
            io: None,
            db_file: None,
            opts: None,
            open_flags: OpenFlags::default(),
            open_db_state: OpenDbAsyncState::new(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum TursoStatusCode {
    Done,
    Row,
    Io,
}

#[derive(Debug, Clone)]
pub enum TursoError {
    Busy(String),
    BusySnapshot(String),
    Interrupt(String),
    Error(String),
    Misuse(String),
    Constraint(String),
    Readonly(String),
    DatabaseFull(String),
    NotAdb(String),
    Corrupt(String),
    IoError(std::io::ErrorKind, &'static str),
}

impl TursoStatusCode {
    pub fn to_capi(self) -> capi::c::turso_status_code_t {
        match self {
            TursoStatusCode::Done => capi::c::turso_status_code_t::TURSO_DONE,
            TursoStatusCode::Row => capi::c::turso_status_code_t::TURSO_ROW,
            TursoStatusCode::Io => capi::c::turso_status_code_t::TURSO_IO,
        }
    }
}

fn result_code_to_result(result: ResultCode, operation: &str) -> Result<(), TursoError> {
    if result.is_ok() {
        Ok(())
    } else {
        Err(TursoError::Error(format!("{operation} failed: {result}")))
    }
}

impl TursoError {
    /// # Safety
    /// error_opt_out must be a valid pointer or null
    pub unsafe fn to_capi(
        &self,
        error_opt_out: *mut *const std::ffi::c_char,
    ) -> capi::c::turso_status_code_t {
        if !error_opt_out.is_null() {
            let message = str_to_c_string(&self.to_string());
            unsafe { *error_opt_out = message };
        }
        self.to_capi_code()
    }
    pub fn to_capi_code(&self) -> capi::c::turso_status_code_t {
        match self {
            TursoError::Busy(_) => capi::c::turso_status_code_t::TURSO_BUSY,
            TursoError::BusySnapshot(_) => capi::c::turso_status_code_t::TURSO_BUSY_SNAPSHOT,
            TursoError::Interrupt(_) => capi::c::turso_status_code_t::TURSO_INTERRUPT,
            TursoError::Error(_) => capi::c::turso_status_code_t::TURSO_ERROR,
            TursoError::Misuse(_) => capi::c::turso_status_code_t::TURSO_MISUSE,
            TursoError::Constraint(_) => capi::c::turso_status_code_t::TURSO_CONSTRAINT,
            TursoError::Readonly(_) => capi::c::turso_status_code_t::TURSO_READONLY,
            TursoError::DatabaseFull(_) => capi::c::turso_status_code_t::TURSO_DATABASE_FULL,
            TursoError::NotAdb(_) => capi::c::turso_status_code_t::TURSO_NOTADB,
            TursoError::Corrupt(_) => capi::c::turso_status_code_t::TURSO_CORRUPT,
            TursoError::IoError(..) => capi::c::turso_status_code_t::TURSO_IOERR,
        }
    }
}

impl Display for TursoError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TursoError::Busy(s)
            | TursoError::BusySnapshot(s)
            | TursoError::Interrupt(s)
            | TursoError::Error(s)
            | TursoError::Misuse(s)
            | TursoError::Constraint(s)
            | TursoError::Readonly(s)
            | TursoError::DatabaseFull(s)
            | TursoError::NotAdb(s)
            | TursoError::Corrupt(s) => f.write_str(s),
            TursoError::IoError(kind, op) => write!(f, "I/O error ({op}): {kind}"),
        }
    }
}

pub fn str_to_c_string(message: &str) -> *const std::ffi::c_char {
    let Ok(message) = std::ffi::CString::new(message) else {
        return std::ptr::null();
    };
    message.into_raw()
}

pub fn c_string_to_str(ptr: *const std::ffi::c_char) -> std::ffi::CString {
    unsafe { std::ffi::CString::from_raw(ptr as *mut std::ffi::c_char) }
}

impl From<LimboError> for TursoError {
    fn from(value: LimboError) -> Self {
        match value {
            LimboError::ForeignKeyConstraint(e) | LimboError::Constraint(e) => {
                TursoError::Constraint(e)
            }
            LimboError::Corrupt(e) => TursoError::Corrupt(e),
            LimboError::NotADB => TursoError::NotAdb("file is not a database".to_string()),
            LimboError::DatabaseFull(e) => TursoError::DatabaseFull(e),
            LimboError::ReadOnly => TursoError::Readonly("database is readonly".to_string()),
            LimboError::Busy => TursoError::Busy("database is locked".to_string()),
            // Same-connection rejections carry SQLITE_BUSY semantics, but the
            // caller must finish/reset its own statement rather than wait.
            err @ LimboError::StatementsInProgress(_) => TursoError::Busy(err.to_string()),
            LimboError::BusySnapshot => TursoError::BusySnapshot(
                "database snapshot is stale, rollback and retry the transaction".to_string(),
            ),
            LimboError::CompletionError(turso_core::CompletionError::IOError(kind, op)) => {
                TursoError::IoError(kind, op)
            }
            _ => TursoError::Error(value.to_string()),
        }
    }
}

fn sync_busy_error() -> TursoError {
    TursoError::Busy("database is locked".to_string())
}

fn sync_operation_active(sync_busy: Option<&Arc<SyncBusyGate>>) -> bool {
    sync_busy.is_some_and(|gate| gate.is_active())
}

fn map_sync_transient_error(
    sync_busy: Option<&Arc<SyncBusyGate>>,
    error: TursoError,
) -> TursoError {
    if sync_busy.is_none() {
        return error;
    }
    match error {
        TursoError::Error(message)
            if message == "Database schema changed"
                || message.starts_with("I/O error: short read on page") =>
        {
            sync_busy_error()
        }
        other => other,
    }
}

static LOGGER: RwLock<Option<Box<Logger>>> = RwLock::new(None);
static SETUP: Once = Once::new();

struct CallbackLayer<F>
where
    F: Fn(TursoLog) + Send + Sync + 'static,
{
    callback: F,
}

impl<S, F> tracing_subscriber::Layer<S> for CallbackLayer<F>
where
    S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
    F: Fn(TursoLog) + Send + Sync + 'static,
{
    fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
        let mut buffer = String::new();
        let mut visitor = fmt::format::DefaultVisitor::new(Writer::new(&mut buffer), true);

        event.record(&mut visitor);

        let log = TursoLog {
            level: event.metadata().level().as_str(),
            target: event.metadata().target(),
            message: &buffer,
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|t| t.as_secs())
                .unwrap_or(0),
            file: event.metadata().file().unwrap_or(""),
            line: event.metadata().line().unwrap_or(0) as usize,
        };

        (self.callback)(log);
    }
}

pub fn turso_setup(config: TursoSetupConfig) -> Result<(), TursoError> {
    fn callback(log: TursoLog<'_>) {
        let Ok(logger) = LOGGER.try_read() else {
            return;
        };

        if let Some(logger) = logger.as_ref() {
            logger(log)
        }
    }

    if let Some(logger) = config.logger {
        let mut guard = LOGGER.write().unwrap();
        *guard = Some(logger);
    }

    let level_filter = if let Some(log_level) = &config.log_level {
        match log_level.as_ref() {
            "error" => Some(LevelFilter::ERROR),
            "warn" => Some(LevelFilter::WARN),
            "info" => Some(LevelFilter::INFO),
            "debug" => Some(LevelFilter::DEBUG),
            "trace" => Some(LevelFilter::TRACE),
            _ => return Err(TursoError::Error("unknown log level".to_string())),
        }
    } else {
        None
    };

    SETUP.call_once(|| {
        if let Some(level_filter) = level_filter {
            tracing_subscriber::registry()
                .with(CallbackLayer { callback }.with_filter(level_filter))
                .init();
        } else {
            tracing_subscriber::registry()
                .with(CallbackLayer { callback }.with_filter(EnvFilter::from_default_env()))
                .init();
        }
    });

    Ok(())
}

impl TursoDatabase {
    /// return turso version
    pub const fn version() -> &'static str {
        env!("CARGO_PKG_VERSION")
    }
    /// method to get [turso_core::Database] instance which can be useful for code which integrates with sdk-kit
    pub fn db_core(&self) -> Result<Arc<turso_core::Database>, TursoError> {
        let db = self.db.lock().unwrap();
        match &*db {
            Some(db) => Ok(db.clone()),
            None => Err(TursoError::Misuse("database must be opened".to_string())),
        }
    }

    /// method to get [turso_core::IO] instance which can be useful for code which integrates with sdk-kit
    pub fn io(&self) -> Result<Arc<dyn turso_core::IO>, TursoError> {
        let io = self.io.lock().unwrap();
        match &*io {
            Some(io) => Ok(io.clone()),
            None => Err(TursoError::Misuse("io must be opened".to_string())),
        }
    }

    /// create database holder struct but do not initialize it yet
    /// this can be useful for some environments, where IO operations must be executed in certain fashion (and open do IO under the hood)
    pub fn new(config: TursoDatabaseConfig) -> Arc<Self> {
        Arc::new(Self {
            config,
            db: Arc::new(Mutex::new(None)),
            open_state: Mutex::new(TursoDatabaseOpenState::new()),
            io: Mutex::new(None),
        })
    }

    /// Get the config IO or open a new vfs IO from the config
    fn open_vfs_io(&self) -> Result<Arc<dyn turso_core::IO>, TursoError> {
        let io: Arc<dyn turso_core::IO + 'static> = if let Some(io) = &self.config.io {
            io.clone()
        } else {
            match self.config.vfs.as_deref() {
                Some("memory") => Arc::new(turso_core::MemoryIO::new()),
                Some("syscall") => {
                    #[cfg(all(target_family = "unix", not(miri)))]
                    {
                        Arc::new(turso_core::UnixIO::new().map_err(|e| {
                            TursoError::Error(format!(
                                "unable to create generic syscall backend: {e}"
                            ))
                        })?)
                    }
                    #[cfg(any(not(target_family = "unix"), miri))]
                    {
                        Arc::new(turso_core::PlatformIO::new().map_err(|e| {
                            TursoError::Error(format!(
                                "unable to create generic syscall backend: {e}"
                            ))
                        })?)
                    }
                }
                #[cfg(all(target_os = "linux", not(miri)))]
                Some("io_uring") => Arc::new(turso_core::UringIO::new().map_err(|e| {
                    TursoError::Error(format!("unable to create io_uring backend: {e}"))
                })?),
                #[cfg(all(target_os = "windows", not(miri)))]
                Some("experimental_win_iocp") => {
                    Arc::new(turso_core::WindowsIOCP::new().map_err(|e| {
                        TursoError::Error(format!("unable to create win_iocp backend: {e}"))
                    })?)
                }
                #[cfg(any(not(target_os = "linux"), miri))]
                Some("io_uring") => {
                    return Err(TursoError::Error(
                        "io_uring is only available on Linux targets".to_string(),
                    ));
                }
                #[cfg(any(not(target_os = "windows"), miri))]
                Some("experimental_win_iocp") => {
                    return Err(TursoError::Error(
                        "win_iocp is only available on Windows targets".to_string(),
                    ));
                }
                Some(vfs) => {
                    Database::io_for_vfs(vfs).map_err(|e| TursoError::Error(format!("{e}")))?
                }
                None => match self.config.path.as_str() {
                    ":memory:" => Arc::new(turso_core::MemoryIO::new()),
                    _ => Arc::new(turso_core::PlatformIO::new()?),
                },
            }
        };
        Ok(io)
    }

    /// Async version of database opening that returns IOResult.
    /// Caller must drive the IO loop and pass state between calls.
    /// This is useful for environments where IO operations must be executed in a specific fashion.
    pub fn open(&self) -> Result<IOResult<()>, TursoError> {
        loop {
            let mut state = self.open_state.lock().unwrap();
            match state.phase {
                TursoDatabaseOpenPhase::Init => {
                    let inner_db = self.db.lock().unwrap();
                    if inner_db.is_some() {
                        return Err(TursoError::Misuse(
                            "database must be opened only once".to_string(),
                        ));
                    }
                    // keep lock for the whole method since open_async must be called only once and never will be called concurrently

                    let io: Arc<dyn turso_core::IO> = self.open_vfs_io()?;

                    // Store the IO so that it can be retrieved with `io()` call even if the database is still opening
                    *self.io.lock().unwrap() = Some(io.clone());

                    // Opts must be computed BEFORE the file open so we can apply
                    // OpenFlags::NoLock when multiprocess WAL is enabled — taking
                    // the OS-level fcntl lock here would block every other
                    // multiprocess process from opening the same file.
                    let opts = self.config.database_opts();

                    if self.config.encryption.is_some() && !opts.enable_encryption {
                        return Err(TursoError::Error(
                            "encryption is experimental and must be explicitly enabled through experimental features list".to_string(),
                        ));
                    }

                    let mut open_flags = OpenFlags::default();
                    if opts.enable_multiprocess_wal {
                        open_flags |= OpenFlags::NoLock;
                    }
                    let db_file = if let Some(db_file) = &self.config.db_file {
                        db_file.clone()
                    } else {
                        let file = io.open_file(&self.config.path, open_flags, true)?;
                        Arc::new(DatabaseFile::new(file))
                    };

                    state.io = Some(io);
                    state.db_file = Some(db_file);
                    state.opts = Some(opts);
                    state.open_flags = open_flags;
                    state.phase = TursoDatabaseOpenPhase::Opening;
                }

                TursoDatabaseOpenPhase::Opening => {
                    let io = state
                        .io
                        .as_ref()
                        .expect("io must be initialized in Init phase")
                        .clone();
                    let db_file = state
                        .db_file
                        .as_ref()
                        .expect("db_file must be initialized in Init phase")
                        .clone();
                    let opts = state.opts.expect("opts must be initialized in Init phase");
                    let open_flags = state.open_flags;

                    match Database::open_with_flags_async(
                        &mut state.open_db_state,
                        io.clone(),
                        &self.config.path,
                        db_file,
                        open_flags,
                        opts,
                        self.config.encryption.clone(),
                        None,
                    )? {
                        IOResult::Done(db) => {
                            let mut inner_db = self.db.lock().unwrap();
                            *inner_db = Some(db);
                            state.phase = TursoDatabaseOpenPhase::Done;
                            return Ok(IOResult::Done(()));
                        }
                        IOResult::IO(io_completion) => {
                            if self.config.async_io {
                                return Ok(IOResult::IO(io_completion));
                            } else {
                                io_completion.wait(io.deref())?;
                            }
                        }
                    }
                }

                TursoDatabaseOpenPhase::Done => {
                    return Ok(IOResult::Done(()));
                }
            }
        }
    }

    /// creates database connection
    /// database must be already opened with [Self::open] method
    pub fn connect(&self) -> Result<Arc<TursoConnection>, TursoError> {
        let inner_db = self.db.lock().unwrap();
        let Some(db) = inner_db.as_ref() else {
            return Err(TursoError::Misuse(
                "database must be opened first".to_string(),
            ));
        };

        // Parse encryption key if configured - needed for connect_with_encryption
        // which sets up encryption context before reading pages
        let encryption_key = if let Some(ref encryption_opts) = self.config.encryption {
            Some(EncryptionKey::from_hex_string(&encryption_opts.hexkey)?)
        } else {
            None
        };

        // Use connect_with_encryption to properly set up encryption context
        // before the pager reads page 1. This is required for encrypted databases.
        let connection = db.connect_with_encryption(encryption_key)?;

        Ok(TursoConnection::new(&self.config, connection))
    }

    /// helper method to get C raw container with TursoDatabase instance
    /// this method is used in the capi wrappers
    pub fn to_capi(self: Arc<Self>) -> *mut capi::c::turso_database_t {
        Arc::into_raw(self) as *mut capi::c::turso_database_t
    }

    /// helper method to restore TursoDatabase ref from C raw container
    /// this method is used in the capi wrappers
    ///
    /// # Safety
    /// value must be a pointer returned from [Self::to_capi] method
    pub unsafe fn ref_from_capi<'a>(
        value: *const capi::c::turso_database_t,
    ) -> Result<&'a Self, TursoError> {
        if value.is_null() {
            Err(TursoError::Misuse("got null pointer".to_string()))
        } else {
            Ok(&*(value as *const Self))
        }
    }

    /// helper method to restore TursoDatabase instance from C raw container
    /// this method is used in the capi wrappers
    ///
    /// # Safety
    /// value must be a pointer returned from [Self::to_capi] method
    pub unsafe fn arc_from_capi(value: *const capi::c::turso_database_t) -> Arc<Self> {
        Arc::from_raw(value as *const Self)
    }
}

struct CachedStatement {
    program: Arc<turso_core::PreparedProgram>,
    query_mode: QueryMode,
}

#[derive(Clone)]
pub struct TursoConnection {
    async_io: bool,
    concurrent_guard: Arc<ConcurrentGuard>,
    connection: Arc<Connection>,
    sync_busy: Option<Arc<SyncBusyGate>>,
    cached_statements: Arc<Mutex<HashMap<String, Arc<CachedStatement>>>>,
    /// Weak refs to every statement handle created by this connection, keyed
    /// by a monotonic ID. Statements remove themselves on drop, so this map
    /// only ever contains live entries. `close()` upgrades each remaining
    /// handle and sets it to `None` to release `Arc<Connection>` → `Arc<Database>`.
    stmts: StmtRegistry,
    next_stmt_id: Arc<AtomicUsize>,
}

impl TursoConnection {
    pub fn new(config: &TursoDatabaseConfig, connection: Arc<Connection>) -> Arc<Self> {
        Self::new_with_sync_busy(config, connection, None)
    }

    pub fn new_with_sync_busy(
        config: &TursoDatabaseConfig,
        connection: Arc<Connection>,
        sync_busy: Option<Arc<SyncBusyGate>>,
    ) -> Arc<Self> {
        Arc::new(Self {
            async_io: config.async_io,
            connection,
            sync_busy,
            concurrent_guard: Arc::new(ConcurrentGuard::new()),
            cached_statements: Arc::new(Mutex::new(HashMap::new())),
            stmts: Arc::new(Mutex::new(HashMap::new())),
            next_stmt_id: Arc::new(AtomicUsize::new(0)),
        })
    }

    fn sync_operation_active(&self) -> bool {
        sync_operation_active(self.sync_busy.as_ref())
    }

    fn map_sync_transient_error(&self, error: TursoError) -> TursoError {
        map_sync_transient_error(self.sync_busy.as_ref(), error)
    }
    /// Set busy timeout for the connection
    pub fn set_busy_timeout(&self, duration: Duration) {
        self.connection.set_busy_timeout(duration);
    }
    /// Request interruption of the statement currently running on this connection.
    /// Mirrors `sqlite3_interrupt`: the in-flight `step`/`execute` aborts with an
    /// `Interrupt` error. Safe to call from another thread. If no statement is
    /// active the request is ignored.
    pub fn interrupt(&self) {
        self.connection.interrupt();
    }
    /// Set the maximum wall-clock duration a single statement is allowed to run
    /// before it is interrupted. `Duration::ZERO` disables the timeout.
    pub fn set_query_timeout(&self, duration: Duration) {
        self.connection.set_query_timeout(duration);
    }
    /// Get the current per-statement query timeout (`Duration::ZERO` when disabled).
    pub fn get_query_timeout(&self) -> Duration {
        self.connection.get_query_timeout()
    }
    pub fn get_auto_commit(&self) -> bool {
        self.connection.get_auto_commit()
    }
    pub fn last_insert_rowid(&self) -> i64 {
        self.connection.last_insert_rowid()
    }

    #[allow(clippy::too_many_arguments)]
    pub fn register_external_scalar_function(
        &self,
        name: String,
        argc: i32,
        deterministic: bool,
        context: usize,
        callback: ScalarFunction,
        context_destructor: Option<ContextDestructor>,
        value_destructor: Option<ValueDestructor>,
    ) -> Result<(), TursoError> {
        let name = CString::new(name).map_err(|err| {
            TursoError::Misuse(format!(
                "external scalar function name contains interior NUL: {err}"
            ))
        })?;
        let api = unsafe { self.connection._build_turso_ext() };
        let result = unsafe {
            (api.register_scalar_function)(
                api.ctx,
                name.as_ptr(),
                argc,
                deterministic,
                context,
                callback,
                context_destructor,
                value_destructor,
            )
        };
        unsafe { self.connection._free_extension_ctx(api) };
        result_code_to_result(result, "register external scalar function")
    }

    #[allow(clippy::too_many_arguments)]
    pub fn register_external_aggregate_function(
        &self,
        name: String,
        argc: i32,
        context: usize,
        init: InitAggFunction,
        step: StepFunction,
        finalize: FinalizeFunction,
        context_destructor: Option<ContextDestructor>,
        aggregate_destructor: Option<ContextDestructor>,
        value_destructor: Option<ValueDestructor>,
    ) -> Result<(), TursoError> {
        let name = CString::new(name).map_err(|err| {
            TursoError::Misuse(format!(
                "external aggregate function name contains interior NUL: {err}"
            ))
        })?;
        let api = unsafe { self.connection._build_turso_ext() };
        let result = unsafe {
            (api.register_aggregate_function)(
                api.ctx,
                name.as_ptr(),
                argc,
                context,
                init,
                step,
                finalize,
                context_destructor,
                aggregate_destructor,
                value_destructor,
            )
        };
        unsafe { self.connection._free_extension_ctx(api) };
        result_code_to_result(result, "register external aggregate function")
    }

    pub fn unregister_external_function(&self, name: &str) -> Result<(), TursoError> {
        let name = CString::new(name).map_err(|err| {
            TursoError::Misuse(format!(
                "external function name contains interior NUL: {err}"
            ))
        })?;
        let api = unsafe { self.connection._build_turso_ext() };
        let result = unsafe { (api.unregister_function)(api.ctx, name.as_ptr()) };
        unsafe { self.connection._free_extension_ctx(api) };
        result_code_to_result(result, "unregister external function")
    }

    pub fn register_external_collation(
        &self,
        name: String,
        context: usize,
        callback: turso_core::ContextCollationFunction,
        context_destructor: Option<ContextDestructor>,
    ) {
        self.connection
            .register_external_collation(name, context, callback, context_destructor);
    }

    pub fn unregister_external_collation(&self, name: &str) {
        self.connection.unregister_external_collation(name);
    }

    pub fn set_load_extension_enabled(&self, enabled: bool) {
        self.connection.set_load_extension_enabled(enabled);
    }

    pub fn load_extension(&self, path: &str) -> Result<(), TursoError> {
        turso_core::resolve_ext_path(path)
            .and_then(|path| self.connection.load_extension(path))
            .map_err(TursoError::from)
    }

    /// prepares single SQL statement
    pub fn prepare_single(&self, sql: impl AsRef<str>) -> Result<Box<TursoStatement>, TursoError> {
        if self.sync_operation_active() {
            return Err(sync_busy_error());
        }
        let statement = self
            .connection
            .prepare(sql)
            .map_err(TursoError::from)
            .map_err(|error| self.map_sync_transient_error(error))?;
        let handle: StatementHandle = Arc::new(Mutex::new(Some(statement)));
        let stmt_id = self.track_stmt(&handle);
        Ok(Box::new(TursoStatement {
            concurrent_guard: self.concurrent_guard.clone(),
            async_io: self.async_io,
            sync_busy: self.sync_busy.clone(),
            handle,
            stmt_id,
            stmts: self.stmts.clone(),
        }))
    }

    /// Prepare a statement from the provided SQL string and cache it for future use.
    pub fn prepare_cached(&self, sql: impl AsRef<str>) -> Result<Box<TursoStatement>, TursoError> {
        if self.sync_operation_active() {
            return Err(sync_busy_error());
        }
        let sql_str = sql.as_ref();

        // Check if we have a cached version
        if let Some(cached) = self.cached_statements.lock().unwrap().get(sql_str) {
            if cached.program.is_compatible_with(&self.connection) {
                let program = turso_core::Program::from_prepared(
                    cached.program.clone(),
                    self.connection.clone(),
                );
                let statement =
                    Statement::new(program, self.connection.get_pager(), cached.query_mode, 0);
                let handle: StatementHandle = Arc::new(Mutex::new(Some(statement)));
                let stmt_id = self.track_stmt(&handle);
                return Ok(Box::new(TursoStatement {
                    concurrent_guard: self.concurrent_guard.clone(),
                    async_io: self.async_io,
                    sync_busy: self.sync_busy.clone(),
                    handle,
                    stmt_id,
                    stmts: self.stmts.clone(),
                }));
            }
        }

        // Not cached, prepare it fresh
        let statement = self
            .connection
            .prepare(sql_str)
            .map_err(TursoError::from)
            .map_err(|error| self.map_sync_transient_error(error))?;

        // Cache it for future use
        let cached = Arc::new(CachedStatement {
            program: statement.get_program().prepared().clone(),
            query_mode: statement.get_query_mode(),
        });
        self.cached_statements
            .lock()
            .unwrap()
            .insert(sql_str.to_string(), cached);

        let handle: StatementHandle = Arc::new(Mutex::new(Some(statement)));
        let stmt_id = self.track_stmt(&handle);
        Ok(Box::new(TursoStatement {
            concurrent_guard: self.concurrent_guard.clone(),
            async_io: self.async_io,
            sync_busy: self.sync_busy.clone(),
            handle,
            stmt_id,
            stmts: self.stmts.clone(),
        }))
    }

    /// prepares first SQL statement from the string and return prepared statement and position after the end of the parsed statement
    /// this method can be useful if SDK provides an execute(...) method which run all statements from the provided input in sequence
    pub fn prepare_first(
        &self,
        sql: impl AsRef<str>,
    ) -> Result<Option<(Box<TursoStatement>, usize)>, TursoError> {
        if self.sync_operation_active() {
            return Err(sync_busy_error());
        }
        match self
            .connection
            .consume_stmt(sql)
            .map_err(TursoError::from)
            .map_err(|error| self.map_sync_transient_error(error))?
        {
            Some((statement, position)) => {
                let handle: StatementHandle = Arc::new(Mutex::new(Some(statement)));
                let stmt_id = self.track_stmt(&handle);
                Ok(Some((
                    Box::new(TursoStatement {
                        async_io: self.async_io,
                        concurrent_guard: Arc::new(ConcurrentGuard::new()),
                        sync_busy: self.sync_busy.clone(),
                        handle,
                        stmt_id,
                        stmts: self.stmts.clone(),
                    }),
                    position,
                )))
            }
            None => Ok(None),
        }
    }

    /// close the connection preventing any further operations executed over it
    /// SAFETY: caller must guarantee that no ongoing operations are running over connection before calling close(...) method
    pub fn close(&self) -> Result<(), TursoError> {
        // Finalize all outstanding statements to release their Arc chain:
        // Statement → Program → Arc<Connection> → Arc<Database>.
        // Without this, un-finalized statements keep the Database alive in
        // DATABASE_MANAGER, causing stale databases after file renames.
        let mut stmts = self.stmts.lock().unwrap();
        for (_id, weak) in stmts.drain() {
            if let Some(handle) = weak.upgrade() {
                // Setting to None drops the turso_core::Statement,
                // releasing Arc<Connection> → Arc<Database>.
                *handle.lock().unwrap() = None;
            }
        }
        self.connection.close()?;
        Ok(())
    }

    /// low-level method used only by the Rust SDK
    pub fn cacheflush(&self) -> Result<(), TursoError> {
        let completions = self.connection.cacheflush()?;
        let pager = self.connection.get_pager();
        for c in completions {
            pager.io.wait_for_completion(c)?;
        }
        Ok(())
    }

    /// helper method to get C raw container to the TursoConnection instance
    /// this method is used in the capi wrappers
    pub fn to_capi(self: Arc<Self>) -> *mut capi::c::turso_connection_t {
        Arc::into_raw(self) as *mut capi::c::turso_connection_t
    }

    /// helper method to restore TursoConnection ref from C raw container
    /// this method is used in the capi wrappers
    ///
    /// # Safety
    /// value must be a pointer returned from [Self::to_capi] method
    pub unsafe fn ref_from_capi<'a>(
        value: *const capi::c::turso_connection_t,
    ) -> Result<&'a Self, TursoError> {
        if value.is_null() {
            Err(TursoError::Misuse("got null pointer".to_string()))
        } else {
            Ok(&*(value as *const Self))
        }
    }

    /// helper method to restore TursoConnection instance from C raw container
    /// this method is used in the capi wrappers
    ///
    /// # Safety
    /// value must be a pointer returned from [Self::to_capi] method
    pub unsafe fn arc_from_capi(value: *const capi::c::turso_connection_t) -> Arc<Self> {
        Arc::from_raw(value as *const Self)
    }

    /// Register a statement handle and return its ID. The statement removes
    /// itself from the registry on drop via its `stmt_id` + `stmts` ref.
    fn track_stmt(&self, handle: &StatementHandle) -> usize {
        let id = self.next_stmt_id.fetch_add(1, Ordering::Relaxed);
        self.stmts
            .lock()
            .unwrap()
            .insert(id, Arc::downgrade(handle));
        id
    }
}

/// Shared ownership of a `turso_core::Statement` that can be explicitly finalized.
/// When the inner `Option` is set to `None`, the statement is considered finalized
/// and all operations on it will return errors / defaults.
pub(crate) type StatementHandle = Arc<Mutex<Option<Statement>>>;
type StmtRegistry = Arc<Mutex<HashMap<usize, Weak<Mutex<Option<Statement>>>>>>;

const FINALIZED_ERR: &str = "statement has been finalized";

/// Advance one step of a statement's execution.
/// Factored out of `TursoStatement` so it can be called while holding
/// the `StatementHandle` lock without re-entrancy issues.
fn step_inner(
    stmt: &mut Statement,
    async_io: bool,
    waker: Option<&Waker>,
) -> Result<TursoStatusCode, TursoError> {
    loop {
        let result = if let Some(waker) = waker {
            stmt.step_with_waker(waker)
        } else {
            stmt.step()
        };
        return match result? {
            StepResult::Done => Ok(TursoStatusCode::Done),
            StepResult::Row => Ok(TursoStatusCode::Row),
            StepResult::Busy => Err(TursoError::Busy("database is locked".to_string())),
            StepResult::Interrupt => Err(TursoError::Interrupt("interrupted".to_string())),
            StepResult::IO | StepResult::Yield => {
                if async_io {
                    Ok(TursoStatusCode::Io)
                } else {
                    stmt._io().step()?;
                    continue;
                }
            }
        };
    }
}

pub struct TursoStatement {
    async_io: bool,
    concurrent_guard: Arc<ConcurrentGuard>,
    sync_busy: Option<Arc<SyncBusyGate>>,
    pub(crate) handle: StatementHandle,
    stmt_id: usize,
    stmts: StmtRegistry,
}

impl Drop for TursoStatement {
    fn drop(&mut self) {
        self.stmts.lock().unwrap().remove(&self.stmt_id);
    }
}

#[derive(Debug, Clone)]
pub struct TursoExecutionResult {
    pub status: TursoStatusCode,
    pub rows_changed: u64,
}

impl TursoStatement {
    /// return amount of row modifications (insert/delete operations) made by the most recent executed statement
    pub fn n_change(&self) -> i64 {
        let handle = self.handle.lock().unwrap();
        match handle.as_ref() {
            Some(stmt) => stmt.n_change(),
            None => 0,
        }
    }
    /// returns parameters count for the statement
    pub fn parameters_count(&self) -> usize {
        let handle = self.handle.lock().unwrap();
        match handle.as_ref() {
            Some(stmt) => stmt.parameters_count(),
            None => 0,
        }
    }
    /// Returns the name of the parameter at the given 1-based index,
    /// including its SQL prefix (e.g. `:name`, `@name`, `$name`).
    /// Returns None for positional-only (`?`) parameters or out-of-range indices.
    pub fn parameter_name(&self, index: usize) -> Option<String> {
        let handle = self.handle.lock().unwrap();
        let stmt = handle.as_ref()?;
        let index = index.try_into().ok()?;
        stmt.parameters().name(index)
    }
    /// binds positional parameter at the corresponding index (1-based)
    pub fn bind_positional(
        &mut self,
        index: usize,
        value: turso_core::Value,
    ) -> Result<(), TursoError> {
        let mut handle = self.handle.lock().unwrap();
        let stmt = handle
            .as_mut()
            .ok_or_else(|| TursoError::Misuse(FINALIZED_ERR.to_string()))?;
        let Ok(index) = index.try_into() else {
            return Err(TursoError::Misuse(
                "bind index must be non-zero".to_string(),
            ));
        };
        if !stmt.parameters().has_slot(index) {
            return Err(TursoError::Misuse(format!(
                "bind index {index} is out of bounds"
            )));
        }
        stmt.bind_at(index, value)?;
        Ok(())
    }
    /// named parameter position.
    ///
    /// The name must include the SQL placeholder prefix, e.g. `:name`, `@name`, `$name`, or `?1`.
    pub fn named_position(&mut self, name: impl AsRef<str>) -> Result<usize, TursoError> {
        let handle = self.handle.lock().unwrap();
        let stmt = handle
            .as_ref()
            .ok_or_else(|| TursoError::Misuse(FINALIZED_ERR.to_string()))?;
        let name = name.as_ref();
        if let Some(index) = stmt.parameter_index(name) {
            return Ok(index.into());
        }

        if name.starts_with('?') {
            let maybe_index = name
                .strip_prefix('?')
                .and_then(|value| value.parse::<usize>().ok())
                .and_then(|value| value.try_into().ok());
            if let Some(index) = maybe_index {
                if stmt.parameters().is_indexed(index) {
                    return Ok(index.into());
                }
            }
        }

        Err(TursoError::Error(format!(
            "named parameter {name} not found"
        )))
    }
    /// make one execution step of the statement
    /// method returns [TursoStatusCode::Done] if execution is finished
    /// method returns [TursoStatusCode::Row] if execution generated a row
    /// method returns [TursoStatusCode::Io] if async_io was set and execution needs IO in order to make progress
    #[inline]
    pub fn step(&mut self, waker: Option<&Waker>) -> Result<TursoStatusCode, TursoError> {
        if sync_operation_active(self.sync_busy.as_ref()) {
            return Err(sync_busy_error());
        }
        let guard = self.concurrent_guard.clone();
        let _guard = guard.try_use()?;
        let mut handle = self.handle.lock().unwrap();
        let stmt = handle
            .as_mut()
            .ok_or_else(|| TursoError::Misuse(FINALIZED_ERR.to_string()))?;
        step_inner(stmt, self.async_io, waker)
            .map_err(|error| map_sync_transient_error(self.sync_busy.as_ref(), error))
    }

    /// execute statement to completion
    /// method returns [TursoStatusCode::Done] if execution completed
    /// method returns [TursoStatusCode::Io] if async_io was set and execution needs IO in order to make progress
    pub fn execute(&mut self, waker: Option<&Waker>) -> Result<TursoExecutionResult, TursoError> {
        if sync_operation_active(self.sync_busy.as_ref()) {
            return Err(sync_busy_error());
        }
        let guard = self.concurrent_guard.clone();
        let _guard = guard.try_use()?;
        let mut handle = self.handle.lock().unwrap();
        let stmt = handle
            .as_mut()
            .ok_or_else(|| TursoError::Misuse(FINALIZED_ERR.to_string()))?;

        loop {
            let status = step_inner(stmt, self.async_io, waker)
                .map_err(|error| map_sync_transient_error(self.sync_busy.as_ref(), error))?;
            if status == TursoStatusCode::Row {
                continue;
            } else if status == TursoStatusCode::Io {
                return Ok(TursoExecutionResult {
                    status,
                    rows_changed: 0,
                });
            } else if status == TursoStatusCode::Done {
                return Ok(TursoExecutionResult {
                    status: TursoStatusCode::Done,
                    rows_changed: stmt.n_change() as u64,
                });
            }
            return Err(TursoError::Error(format!(
                "internal error: unexpected status code: {status:?}",
            )));
        }
    }
    /// run iteration of the IO backend
    pub fn run_io(&self) -> Result<(), TursoError> {
        let handle = self.handle.lock().unwrap();
        let stmt = handle
            .as_ref()
            .ok_or_else(|| TursoError::Misuse(FINALIZED_ERR.to_string()))?;
        stmt._io().step()?;
        Ok(())
    }
    /// get row value as an owned Value
    #[inline]
    pub fn row_value(&self, index: usize) -> Result<turso_core::Value, TursoError> {
        if sync_operation_active(self.sync_busy.as_ref()) {
            return Err(sync_busy_error());
        }
        let handle = self.handle.lock().unwrap();
        let stmt = handle
            .as_ref()
            .ok_or_else(|| TursoError::Misuse(FINALIZED_ERR.to_string()))?;
        let Some(row) = stmt.row() else {
            return Err(TursoError::Misuse("statement holds no row".to_string()));
        };
        if index >= row.len() {
            return Err(TursoError::Misuse(
                "attempt to access row value out of bounds".to_string(),
            ));
        }
        Ok(row.get_value(index).as_value_ref().to_owned())
    }
    /// returns column count
    pub fn column_count(&self) -> usize {
        let handle = self.handle.lock().unwrap();
        match handle.as_ref() {
            Some(stmt) => stmt.num_columns(),
            None => 0,
        }
    }
    /// returns column name
    pub fn column_name(&self, index: usize) -> Result<String, TursoError> {
        let handle = self.handle.lock().unwrap();
        let stmt = handle
            .as_ref()
            .ok_or_else(|| TursoError::Misuse(FINALIZED_ERR.to_string()))?;
        if index >= stmt.num_columns() {
            return Err(TursoError::Misuse("column index out of bounds".to_string()));
        }
        Ok(stmt.get_column_name(index).into_owned())
    }
    /// returns column declared type (e.g. "INTEGER", "TEXT", "DATETIME", etc.)
    pub fn column_decltype(&self, index: usize) -> Option<String> {
        let handle = self.handle.lock().unwrap();
        let stmt = handle.as_ref()?;
        if index >= stmt.num_columns() {
            return None;
        }
        stmt.get_column_decltype(index)
    }

    /// Returns rich type information for the column at `index`.
    ///
    /// Wraps [`turso_core::Statement::get_column_type_info`]. Returns `None`
    /// when the statement has been finalized, when the index is out of
    /// bounds, when the connection does not have the experimental custom-
    /// types feature enabled (the underlying call errors and we surface that
    /// as "no info"; the C ABI has no error channel), when the statement is
    /// in EXPLAIN mode, or when the expression behind the column has no
    /// determined affinity.
    pub fn column_type_info(&self, index: usize) -> Option<turso_core::ColumnTypeInfo> {
        let handle = self.handle.lock().unwrap();
        let stmt = handle.as_ref()?;
        if index >= stmt.num_columns() {
            return None;
        }
        stmt.get_column_type_info(index).ok().flatten()
    }
    /// finalize statement execution
    /// this method must be called in the end of statement execution (either successfull or not)
    pub fn finalize(&mut self, waker: Option<&Waker>) -> Result<TursoStatusCode, TursoError> {
        let guard = self.concurrent_guard.clone();
        let _guard = guard.try_use()?;
        let mut handle = self.handle.lock().unwrap();
        if let Some(stmt) = handle.as_mut() {
            while stmt.execution_state().is_running() {
                let status = step_inner(stmt, self.async_io, waker)?;
                if status == TursoStatusCode::Io {
                    return Ok(status);
                }
            }
        }
        // Drop the inner statement to release the Arc chain
        *handle = None;
        Ok(TursoStatusCode::Done)
    }
    /// reset internal statement state and bindings
    pub fn reset(&mut self) -> Result<(), TursoError> {
        let mut handle = self.handle.lock().unwrap();
        let stmt = handle
            .as_mut()
            .ok_or_else(|| TursoError::Misuse(FINALIZED_ERR.to_string()))?;
        stmt.reset()?;
        stmt.clear_bindings();
        Ok(())
    }

    /// helper method to get C raw container to the TursoStatement instance
    /// this method is used in the capi wrappers
    pub fn to_capi(self: Box<Self>) -> *mut capi::c::turso_statement_t {
        Box::into_raw(self) as *mut capi::c::turso_statement_t
    }

    /// helper method to restore TursoStatement ref from C raw container
    /// this method is used in the capi wrappers
    ///
    /// # Safety
    /// value must be a pointer returned from [Self::to_capi] method
    pub unsafe fn ref_from_capi<'a>(
        value: *const capi::c::turso_statement_t,
    ) -> Result<&'a mut Self, TursoError> {
        if value.is_null() {
            Err(TursoError::Misuse("got null pointer".to_string()))
        } else {
            Ok(&mut *(value as *mut Self))
        }
    }

    /// helper method to restore TursoStatement instance from C raw container
    /// this method is used in the capi wrappers
    ///
    /// # Safety
    /// value must be a pointer returned from [Self::to_capi] method
    pub unsafe fn box_from_capi(value: *const capi::c::turso_statement_t) -> Box<Self> {
        Box::from_raw(value as *mut Self)
    }
}

#[cfg(test)]
mod tests {
    use crate::rsapi::{
        TursoDatabase, TursoDatabaseConfig, TursoError, TursoStatusCode, FINALIZED_ERR,
    };
    use turso_core::Value;

    fn config_with_features(features: Option<&str>) -> TursoDatabaseConfig {
        TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: features.map(str::to_string),
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        }
    }

    #[test]
    pub fn database_opts_maps_experimental_features() {
        // No features -> all defaults.
        assert_eq!(
            config_with_features(None).database_opts(),
            turso_core::DatabaseOpts::new()
        );

        // Each token toggles its corresponding flag.
        let opts = config_with_features(Some(
            "views,index_method,custom_types,autovacuum,vacuum,encryption,attach,generated_columns,multiprocess_wal,without_rowid",
        ))
        .database_opts();
        assert!(opts.enable_views);
        assert!(opts.enable_index_method);
        assert!(opts.enable_custom_types);
        assert!(opts.enable_autovacuum);
        assert!(opts.enable_vacuum);
        assert!(opts.enable_encryption);
        assert!(opts.enable_attach);
        assert!(opts.enable_generated_columns);
        assert!(opts.enable_multiprocess_wal);
        assert!(opts.enable_without_rowid);

        // Whitespace is trimmed; `strict` and unknown names are ignored.
        let opts = config_with_features(Some(" views , strict , unknown_one ")).database_opts();
        assert!(opts.enable_views);
        assert_eq!(
            config_with_features(Some("strict,unknown")).database_opts(),
            turso_core::DatabaseOpts::new()
        );
    }

    #[test]
    pub fn test_db_concurrent_use() {
        use std::sync::{Arc, Barrier};

        let mut errors = Vec::new();
        for _ in 0..16 {
            let db = TursoDatabase::new(TursoDatabaseConfig {
                path: ":memory:".to_string(),
                experimental_features: None,
                async_io: false,
                encryption: None,
                vfs: None,
                io: None,
                db_file: None,
            });
            let result = db.open().unwrap();
            assert!(!result.is_io());
            let conn = db.connect().unwrap();
            let stmt1 = conn
                .prepare_single("SELECT * FROM generate_series(1, 100000)")
                .unwrap();
            let stmt2 = conn
                .prepare_single("SELECT * FROM generate_series(1, 100000)")
                .unwrap();

            // Use a barrier to ensure both threads start executing at the same time
            let barrier = Arc::new(Barrier::new(2));
            let mut threads = Vec::new();
            for mut stmt in [stmt1, stmt2] {
                let barrier_clone = Arc::clone(&barrier);
                let thread = std::thread::spawn(move || {
                    barrier_clone.wait();
                    stmt.execute(None)
                });
                threads.push(thread);
            }
            let mut results = Vec::new();
            for thread in threads {
                results.push(thread.join().unwrap());
            }
            assert!(
                !(results[0].is_err() && results[1].is_err()),
                "results: {results:?}",
            );
            if results[0].is_err() || results[1].is_err() {
                errors.push(
                    results[0]
                        .clone()
                        .err()
                        .or(results[1].clone().err())
                        .unwrap(),
                );
            }
        }
        println!("{errors:?}");
        assert!(
            !errors.is_empty(),
            "misuse errors should be very likely with the test setup: {errors:?}"
        );
        assert!(
            errors.iter().all(|e| matches!(e, TursoError::Misuse(_))),
            "all errors must have Misuse code: {errors:?}"
        );
    }

    #[test]
    pub fn test_db_rsapi_use() {
        let db = TursoDatabase::new(TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let result = db.open().unwrap();
        assert!(!result.is_io());
        let conn = db.connect().unwrap();
        let mut stmt = conn
            .prepare_single("SELECT * FROM generate_series(1, 10000)")
            .unwrap();
        assert_eq!(stmt.execute(None).unwrap().status, TursoStatusCode::Done);
    }

    #[test]
    pub fn test_named_position_requires_prefixed_name() {
        let db = TursoDatabase::new(TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let result = db.open().unwrap();
        assert!(!result.is_io());

        let conn = db.connect().unwrap();
        let mut stmt = conn
            .prepare_single("SELECT :new_name, @other_name, $third_name")
            .unwrap();

        assert_eq!(stmt.named_position(":new_name").unwrap(), 1);
        assert!(stmt.named_position("new_name").is_err());
        assert!(stmt.named_position("?1").is_err());

        assert_eq!(stmt.named_position("@other_name").unwrap(), 2);
        assert!(stmt.named_position("other_name").is_err());

        assert_eq!(stmt.named_position("$third_name").unwrap(), 3);
        assert!(stmt.named_position("third_name").is_err());
    }

    #[test]
    pub fn test_bind_positional_rejects_out_of_bounds_index() {
        let db = TursoDatabase::new(TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let result = db.open().unwrap();
        assert!(!result.is_io());

        let conn = db.connect().unwrap();
        let mut stmt = conn.prepare_single("SELECT ?1").unwrap();

        stmt.bind_positional(1, Value::from_i64(42)).unwrap();

        let err = stmt.bind_positional(2, Value::from_i64(7)).unwrap_err();
        assert!(matches!(err, TursoError::Misuse(_)));
    }

    #[test]
    pub fn test_execute_update_with_prefixed_named_parameters() {
        let db = TursoDatabase::new(TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let result = db.open().unwrap();
        assert!(!result.is_io());

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

        let mut create_stmt = conn
            .prepare_single("CREATE TABLE simple (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
            .unwrap();
        assert_eq!(
            create_stmt.execute(None).unwrap().status,
            TursoStatusCode::Done
        );

        let mut insert_stmt = conn
            .prepare_single("INSERT INTO simple (name) VALUES ('original_name')")
            .unwrap();
        assert_eq!(
            insert_stmt.execute(None).unwrap().status,
            TursoStatusCode::Done
        );

        let mut update_stmt = conn
            .prepare_single("UPDATE simple SET name = :new_name WHERE name = :old_name")
            .unwrap();

        let new_name_position = update_stmt.named_position(":new_name").unwrap();
        update_stmt
            .bind_positional(new_name_position, Value::build_text("updated_name"))
            .unwrap();
        let old_name_position = update_stmt.named_position(":old_name").unwrap();
        update_stmt
            .bind_positional(old_name_position, Value::build_text("original_name"))
            .unwrap();

        let update_result = update_stmt.execute(None).unwrap();
        assert_eq!(update_result.status, TursoStatusCode::Done);
        assert_eq!(update_result.rows_changed, 1);
    }

    #[test]
    pub fn test_execute_update_with_mixed_placeholders() {
        let db = TursoDatabase::new(TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let result = db.open().unwrap();
        assert!(!result.is_io());

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

        let mut create_stmt = conn
            .prepare_single("CREATE TABLE mixed (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT, age INTEGER)")
            .unwrap();
        assert_eq!(
            create_stmt.execute(None).unwrap().status,
            TursoStatusCode::Done
        );

        let mut insert_stmt = conn
            .prepare_single(
                "INSERT INTO mixed (name, email, age) VALUES ('alice', 'alice@old.com', 25)",
            )
            .unwrap();
        assert_eq!(
            insert_stmt.execute(None).unwrap().status,
            TursoStatusCode::Done
        );

        let mut update_stmt = conn
            .prepare_single("UPDATE mixed SET email = ?, age = :new_age WHERE name = ?")
            .unwrap();

        assert_eq!(update_stmt.named_position("?1").unwrap(), 1);
        assert_eq!(update_stmt.named_position(":new_age").unwrap(), 2);
        assert!(update_stmt.named_position("new_age").is_err());
        assert_eq!(update_stmt.named_position("?3").unwrap(), 3);

        update_stmt
            .bind_positional(1, Value::build_text("alice@new.com"))
            .unwrap();
        let age_position = update_stmt.named_position(":new_age").unwrap();
        update_stmt
            .bind_positional(age_position, Value::from_i64(30))
            .unwrap();
        update_stmt
            .bind_positional(3, Value::build_text("alice"))
            .unwrap();

        let update_result = update_stmt.execute(None).unwrap();
        assert_eq!(update_result.status, TursoStatusCode::Done);
        assert_eq!(update_result.rows_changed, 1);
    }

    #[test]
    pub fn test_select_named_and_positional_mapping_stays_sql_order() {
        let db = TursoDatabase::new(TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let result = db.open().unwrap();
        assert!(!result.is_io());

        let conn = db.connect().unwrap();
        let mut create_stmt = conn
            .prepare_single("CREATE TABLE simple (name TEXT NOT NULL)")
            .unwrap();
        assert_eq!(
            create_stmt.execute(None).unwrap().status,
            TursoStatusCode::Done
        );

        let mut stmt = conn
            .prepare_single("SELECT :named FROM simple WHERE name = ?")
            .unwrap();

        assert_eq!(stmt.named_position(":named").unwrap(), 1);
        assert!(stmt.named_position("named").is_err());
        assert_eq!(stmt.named_position("?2").unwrap(), 2);
    }

    #[test]
    pub fn test_named_and_indexed_alias_share_slot() {
        let db = TursoDatabase::new(TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let result = db.open().unwrap();
        assert!(!result.is_io());

        let conn = db.connect().unwrap();
        let mut stmt = conn
            .prepare_single("SELECT :v AS named_slot, ?1 AS pos_slot")
            .unwrap();

        assert_eq!(stmt.named_position(":v").unwrap(), 1);
        assert!(stmt.named_position("v").is_err());
        assert!(stmt.named_position("?1").is_err());

        stmt.bind_positional(1, Value::from_i64(7)).unwrap();
        assert_eq!(stmt.step(None).unwrap(), TursoStatusCode::Row);
        assert_eq!(stmt.row_value(0).unwrap().as_int(), Some(7));
        assert_eq!(stmt.row_value(1).unwrap().as_int(), Some(7));
    }

    #[test]
    pub fn test_sparse_positional_index_uses_declared_slot() {
        let db = TursoDatabase::new(TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let result = db.open().unwrap();
        assert!(!result.is_io());

        let conn = db.connect().unwrap();
        let mut stmt = conn.prepare_single("SELECT ?3").unwrap();

        assert_eq!(stmt.parameters_count(), 3);
        stmt.bind_positional(1, Value::from_i64(1)).unwrap();

        stmt.bind_positional(3, Value::from_i64(9)).unwrap();
        assert_eq!(stmt.step(None).unwrap(), TursoStatusCode::Row);
        assert_eq!(stmt.row_value(0).unwrap().as_int(), Some(9));
    }

    #[test]
    pub fn test_sparse_positional_index_count_matches_sqlite() {
        let db = TursoDatabase::new(TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let result = db.open().unwrap();
        assert!(!result.is_io());

        let conn = db.connect().unwrap();
        let mut stmt = conn.prepare_single("SELECT ?3").unwrap();

        assert_eq!(stmt.parameters_count(), 3);
        assert!(stmt.named_position("?1").is_err());
        assert_eq!(stmt.named_position("?3").unwrap(), 3);

        stmt.bind_positional(3, Value::from_i64(11)).unwrap();
        assert_eq!(stmt.step(None).unwrap(), TursoStatusCode::Row);
        assert_eq!(stmt.row_value(0).unwrap().as_int(), Some(11));
    }

    #[test]
    pub fn test_insert_with_mixed_placeholders() {
        let db = TursoDatabase::new(TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let result = db.open().unwrap();
        assert!(!result.is_io());

        let conn = db.connect().unwrap();
        let mut create_stmt = conn
            .prepare_single("CREATE TABLE users (name TEXT NOT NULL, age INTEGER NOT NULL)")
            .unwrap();
        assert_eq!(
            create_stmt.execute(None).unwrap().status,
            TursoStatusCode::Done
        );

        let mut insert_stmt = conn
            .prepare_single("INSERT INTO users (name, age) VALUES (?, :age)")
            .unwrap();

        assert_eq!(insert_stmt.named_position("?1").unwrap(), 1);
        assert_eq!(insert_stmt.named_position(":age").unwrap(), 2);
        assert!(insert_stmt.named_position("age").is_err());

        insert_stmt
            .bind_positional(1, Value::build_text("alice"))
            .unwrap();
        let age_position = insert_stmt.named_position(":age").unwrap();
        insert_stmt
            .bind_positional(age_position, Value::from_i64(30))
            .unwrap();

        let insert_result = insert_stmt.execute(None).unwrap();
        assert_eq!(insert_result.status, TursoStatusCode::Done);
        assert_eq!(insert_result.rows_changed, 1);

        let mut verify_stmt = conn
            .prepare_single("SELECT age FROM users WHERE name = 'alice'")
            .unwrap();
        assert_eq!(verify_stmt.step(None).unwrap(), TursoStatusCode::Row);
        assert_eq!(verify_stmt.row_value(0).unwrap().as_int(), Some(30));
    }

    #[test]
    pub fn test_delete_with_mixed_placeholders() {
        let db = TursoDatabase::new(TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let result = db.open().unwrap();
        assert!(!result.is_io());

        let conn = db.connect().unwrap();
        let mut create_stmt = conn
            .prepare_single("CREATE TABLE users (name TEXT NOT NULL, age INTEGER NOT NULL)")
            .unwrap();
        assert_eq!(
            create_stmt.execute(None).unwrap().status,
            TursoStatusCode::Done
        );

        let mut seed_stmt = conn
            .prepare_single("INSERT INTO users (name, age) VALUES ('alice', 30), ('bob', 40)")
            .unwrap();
        assert_eq!(
            seed_stmt.execute(None).unwrap().status,
            TursoStatusCode::Done
        );

        let mut delete_stmt = conn
            .prepare_single("DELETE FROM users WHERE name = ? AND age = :age")
            .unwrap();

        assert_eq!(delete_stmt.named_position("?1").unwrap(), 1);
        assert_eq!(delete_stmt.named_position(":age").unwrap(), 2);
        assert!(delete_stmt.named_position("age").is_err());

        delete_stmt
            .bind_positional(1, Value::build_text("alice"))
            .unwrap();
        let age_position = delete_stmt.named_position(":age").unwrap();
        delete_stmt
            .bind_positional(age_position, Value::from_i64(30))
            .unwrap();

        let delete_result = delete_stmt.execute(None).unwrap();
        assert_eq!(delete_result.status, TursoStatusCode::Done);
        assert_eq!(delete_result.rows_changed, 1);

        let mut verify_stmt = conn.prepare_single("SELECT count(*) FROM users").unwrap();
        assert_eq!(verify_stmt.step(None).unwrap(), TursoStatusCode::Row);
        assert_eq!(verify_stmt.row_value(0).unwrap().as_int(), Some(1));
    }

    #[cfg(feature = "encryption")]
    mod encryption_tests {
        use super::*;
        use tempfile::NamedTempFile;

        const TEST_CIPHER: &str = "aes256gcm";
        const TEST_HEXKEY: &str =
            "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
        const WRONG_HEXKEY: &str =
            "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";

        fn create_encryption_opts() -> crate::rsapi::EncryptionOpts {
            crate::rsapi::EncryptionOpts {
                cipher: TEST_CIPHER.to_string(),
                hexkey: TEST_HEXKEY.to_string(),
            }
        }

        fn assert_integer(value: turso_core::Value, expected: i64) {
            match value {
                turso_core::Value::Numeric(turso_core::Numeric::Integer(i)) => {
                    assert_eq!(i, expected)
                }
                _ => panic!("Expected integer {expected}, got {value:?}"),
            }
        }

        #[test]
        fn test_encryption() {
            let temp_file = NamedTempFile::new().unwrap();
            let db_path = temp_file.path().to_str().unwrap();

            // 1. Create encrypted database and insert data
            {
                let db = TursoDatabase::new(TursoDatabaseConfig {
                    path: db_path.to_string(),
                    experimental_features: Some("encryption".to_string()),
                    async_io: false,
                    encryption: Some(create_encryption_opts()),
                    vfs: None,
                    io: None,
                    db_file: None,
                });
                let result = db.open().unwrap();
                assert!(!result.is_io());
                let conn = db.connect().unwrap();

                let mut stmt = conn
                    .prepare_single("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)")
                    .unwrap();
                stmt.execute(None).unwrap();

                let mut stmt = conn
                    .prepare_single("INSERT INTO test (id, value) VALUES (1, 'secret_data')")
                    .unwrap();
                stmt.execute(None).unwrap();

                // Checkpoint to ensure data is written to main db file
                let mut stmt = conn
                    .prepare_single("PRAGMA wal_checkpoint(TRUNCATE)")
                    .unwrap();
                stmt.execute(None).unwrap();
            }

            // 2. Verify data is encrypted on disk
            let content = std::fs::read(db_path).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 db = TursoDatabase::new(TursoDatabaseConfig {
                    path: db_path.to_string(),
                    experimental_features: Some("encryption".to_string()),
                    async_io: false,
                    encryption: Some(create_encryption_opts()),
                    vfs: None,
                    io: None,
                    db_file: None,
                });
                let result = db.open().unwrap();
                assert!(!result.is_io());
                let conn = db.connect().unwrap();

                let mut stmt = conn
                    .prepare_single("SELECT id, value FROM test WHERE id = 1")
                    .unwrap();
                assert_eq!(stmt.step(None).unwrap(), TursoStatusCode::Row);
                assert_integer(stmt.row_value(0).unwrap(), 1);
                assert_eq!(stmt.row_value(1).unwrap().to_text(), Some("secret_data"));
            }

            // 4. Verify opening with wrong key fails
            {
                let db = TursoDatabase::new(TursoDatabaseConfig {
                    path: db_path.to_string(),
                    experimental_features: Some("encryption".to_string()),
                    async_io: false,
                    encryption: Some(crate::rsapi::EncryptionOpts {
                        cipher: TEST_CIPHER.to_string(),
                        hexkey: WRONG_HEXKEY.to_string(),
                    }),
                    vfs: None,
                    io: None,
                    db_file: None,
                });
                assert!(db.open().is_err(), "Opening with wrong key should fail");
            }

            // 5. Verify opening without encryption fails
            {
                let db = TursoDatabase::new(TursoDatabaseConfig {
                    path: db_path.to_string(),
                    experimental_features: Some("encryption".to_string()),
                    async_io: false,
                    encryption: None,
                    vfs: None,
                    io: None,
                    db_file: None,
                });
                let result = db.open();
                println!("result: {result:?}");
                assert!(
                    result.is_err(),
                    "Opening encrypted database without key should fail"
                );
            }
        }
    }

    /// Reproducer: stale DATABASE_MANAGER entry when old TursoDatabase/TursoConnection
    /// haven't been GC'd (dropped) before reopening at the same path.
    ///
    /// Steps (mirrors the React Native bug report):
    ///   1. Open database A via SDK, create table "cache", close connection
    ///   2. Copy A.db → B.db, delete A.db
    ///   3. Open a *new* database at path A.db — while old db_a/conn_a still alive
    ///   4. CREATE TABLE cache should succeed (A.db is fresh) but fails with
    ///      "table cache already exists" because the registry returned the stale Database
    #[test]
    pub fn test_stale_registry_with_live_sdk_handles() {
        let tmp_dir = tempfile::TempDir::new().unwrap();
        let path_a = tmp_dir.path().join("A.db");
        let path_b = tmp_dir.path().join("B.db");

        // 1. Open database A via SDK and create a table.
        let db_a = TursoDatabase::new(TursoDatabaseConfig {
            path: path_a.to_str().unwrap().to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let _ = db_a.open().unwrap();
        let conn_a = db_a.connect().unwrap();

        let mut stmt = conn_a
            .prepare_single("CREATE TABLE cache(x INTEGER)")
            .unwrap();
        assert_eq!(stmt.execute(None).unwrap().status, TursoStatusCode::Done);
        drop(stmt);

        // Close the connection but do NOT drop conn_a or db_a — simulates
        // the JS GC not having collected them yet.
        conn_a.close().unwrap();

        // 2. Copy A.db → B.db, then delete A.db (and WAL/SHM files).
        std::fs::copy(&path_a, &path_b).unwrap();
        std::fs::remove_file(&path_a).unwrap();
        for ext in &["-wal", "-shm"] {
            let src = tmp_dir.path().join(format!("A.db{ext}"));
            let dst = tmp_dir.path().join(format!("B.db{ext}"));
            if src.exists() {
                std::fs::copy(&src, &dst).unwrap();
                std::fs::remove_file(&src).unwrap();
            }
        }

        // 3. Open a new database at the same path A.db.
        //    The old db_a and conn_a are still alive — this is the key difference
        //    from test_sdk_close_finalizes_leaked_statements which drops everything.
        let db_a2 = TursoDatabase::new(TursoDatabaseConfig {
            path: path_a.to_str().unwrap().to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let _ = db_a2.open().unwrap();
        let conn_a2 = db_a2.connect().unwrap();

        // 4. A.db should be a fresh empty database — CREATE TABLE cache must succeed.
        let mut stmt2 = conn_a2
            .prepare_single("CREATE TABLE cache(x INTEGER)")
            .expect("prepare should succeed on fresh database");
        let result = stmt2.execute(None);
        assert_eq!(
            result.unwrap().status,
            TursoStatusCode::Done,
            "CREATE TABLE cache on a fresh A.db should succeed — \
             stale DATABASE_MANAGER entry returned the old Database"
        );

        // Cleanup: drop old handles (simulates eventual GC).
        drop(conn_a);
        drop(db_a);
    }

    /// Regression test: connection.close() must finalize all outstanding statements
    /// to break the Statement → Arc<Connection> → Arc<Database> chain that keeps the
    /// database alive in DATABASE_MANAGER after a file rename.
    #[test]
    pub fn test_close_finalizes_outstanding_statements() {
        let db = TursoDatabase::new(TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let result = db.open().unwrap();
        assert!(!result.is_io());

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

        // Create a statement but do NOT finalize or drop it
        let mut stmt = conn.prepare_single("SELECT 1").unwrap();
        assert_eq!(stmt.step(None).unwrap(), TursoStatusCode::Row);

        // close() should finalize the outstanding statement
        conn.close().unwrap();

        // The statement should now be finalized — using it returns an error
        let result = stmt.step(None);
        assert!(result.is_err());
        match result.unwrap_err() {
            TursoError::Misuse(msg) => assert_eq!(msg, FINALIZED_ERR),
            other => panic!("expected Misuse error, got: {other:?}"),
        }
    }

    /// Test that finalize() sets the statement handle to None, making subsequent
    /// operations return "statement has been finalized".
    #[test]
    pub fn test_finalize_disposes_statement() {
        let db = TursoDatabase::new(TursoDatabaseConfig {
            path: ":memory:".to_string(),
            experimental_features: None,
            async_io: false,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        });
        let result = db.open().unwrap();
        assert!(!result.is_io());

        let conn = db.connect().unwrap();
        let mut stmt = conn.prepare_single("SELECT 1").unwrap();

        // Finalize the statement
        assert_eq!(stmt.finalize(None).unwrap(), TursoStatusCode::Done);

        // All operations should now return "statement has been finalized"
        assert!(stmt.step(None).is_err());
        assert!(stmt.execute(None).is_err());
        assert!(stmt.reset().is_err());
        assert!(stmt.run_io().is_err());
        assert!(stmt.bind_positional(1, Value::Null).is_err());
        assert_eq!(stmt.n_change(), 0);
        assert_eq!(stmt.column_count(), 0);
        assert_eq!(stmt.parameters_count(), 0);
    }
}