exarrow-rs 0.28.0

ADBC-compatible driver for Exasol with Arrow data format support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
//! ADBC Connection implementation.
//!
//! This module provides the `Connection` type which represents an active
//! database connection and provides methods for executing queries.
//!
//! # New in v2.0.0
//!
//! Connection now owns the transport directly and Statement is a pure data container.
//! Execute statements via Connection methods: `execute_statement()`, `execute_prepared()`.

use crate::adbc::Statement;
use crate::connection::auth::AuthResponseData;
use crate::connection::params::ConnectionParams;
use crate::connection::session::{Session as SessionInfo, SessionConfig};
use crate::error::{ConnectionError, ExasolError, QueryError, TransportError};
use crate::query::prepared::PreparedStatement;
use crate::query::results::ResultSet;
use crate::query::statement::Parameter;
use crate::transport::protocol::{
    ConnectionParams as TransportConnectionParams, Credentials as TransportCredentials,
    QueryResult, TransportProtocol,
};
use arrow::array::RecordBatch;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use tokio::runtime::Runtime;
use tokio::sync::Mutex;

/// Session is a type alias for Connection.
///
/// This alias provides a more intuitive name for database sessions when
/// performing import/export operations. Both `Session` and `Connection`
/// can be used interchangeably.
///
/// # Example
///
pub type Session = Connection;

/// Round a duration up to whole seconds over its millisecond value.
///
/// Any positive sub-second duration maps to at least `1`; only a zero duration
/// maps to `0`. Exasol treats `queryTimeout = 0` as "unlimited", so `0` is
/// reserved exclusively for the no-timeout / reset path — a caller-requested
/// near-zero-but-nonzero timeout must never collapse into that sentinel.
fn secs_ceil(d: Duration) -> u64 {
    let secs = d.as_secs();
    if d.subsec_nanos() > 0 {
        secs.saturating_add(1)
    } else {
        secs
    }
}

/// Map a transport-layer execution failure to a [`QueryError`].
///
/// A server-reported query-timeout abort carries Exasol SQL state `R0001`
/// ("Query terminated because timeout has been reached."). Such a failure maps
/// to [`QueryError::Timeout`], matched primarily on the SQL state code with the
/// message text as a fallback; every other failure maps to
/// [`QueryError::ExecutionFailed`].
///
/// `timeout_ms` is the effective timeout actually enforced by the server for
/// this statement (`0` when none was configured). An `R0001` abort is only
/// classified as [`QueryError::Timeout`] when a non-zero timeout was in
/// effect — an ambient session-level `QUERY_TIMEOUT` firing on a statement the
/// driver never limited surfaces as [`QueryError::ExecutionFailed`] instead,
/// preserving the server's message rather than reporting a nonsensical
/// "timeout after 0ms".
fn map_execution_error(err: TransportError, timeout_ms: u64) -> QueryError {
    let message = err.to_string();
    let is_query_timeout = timeout_ms > 0
        && (message.contains("R0001")
            || message.contains("Query terminated because timeout has been reached"));
    if is_query_timeout {
        QueryError::Timeout { timeout_ms }
    } else {
        QueryError::ExecutionFailed(message)
    }
}

fn blocking_runtime() -> &'static Runtime {
    static RUNTIME: OnceLock<Runtime> = OnceLock::new();
    RUNTIME.get_or_init(|| {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("Failed to create tokio runtime for blocking operations")
    })
}

/// ADBC Connection to an Exasol database.
///
/// The `Connection` type represents an active database connection and provides
/// methods for executing queries, managing transactions, and retrieving metadata.
///
/// # v2.0.0 Breaking Changes
///
/// - Connection now owns the transport directly
/// - `create_statement()` is now synchronous and returns a pure data container
/// - Use `execute_statement()` instead of `Statement::execute()`
/// - Use `prepare()` instead of `Statement::prepare()`
///
/// # Example
///
pub struct Connection {
    /// Transport layer for communication (owned by Connection)
    transport: Arc<Mutex<dyn TransportProtocol>>,
    /// Session information
    session: SessionInfo,
    /// Connection parameters
    params: ConnectionParams,
}

impl Connection {
    /// Create a connection from connection parameters.
    ///
    /// This establishes a connection to the Exasol database using WebSocket transport,
    /// authenticates the user, and creates a session.
    ///
    /// # Arguments
    ///
    /// * `params` - Connection parameters
    ///
    /// # Returns
    ///
    /// A connected `Connection` instance.
    ///
    /// # Errors
    ///
    /// Returns `ConnectionError` if the connection or authentication fails.
    pub async fn from_params(params: ConnectionParams) -> Result<Self, ConnectionError> {
        let requested = params.transport.as_deref();

        match requested {
            #[cfg(feature = "native")]
            Some("native") | None => {
                let transport = crate::transport::NativeTcpTransport::new();
                Self::connect_with_transport(params, transport).await
            }
            #[cfg(feature = "websocket")]
            Some("websocket") => {
                let transport = crate::transport::WebSocketTransport::new();
                Self::connect_with_transport(params, transport).await
            }
            #[cfg(all(not(feature = "native"), feature = "websocket"))]
            None => {
                let transport = crate::transport::WebSocketTransport::new();
                Self::connect_with_transport(params, transport).await
            }
            Some(t) => Err(ConnectionError::InvalidParameter {
                parameter: "transport".to_string(),
                message: format!("Transport '{}' is not available. Check feature flags.", t),
            }),
            #[cfg(not(any(feature = "native", feature = "websocket")))]
            None => Err(ConnectionError::InvalidParameter {
                parameter: "transport".to_string(),
                message: "No transport feature enabled. Enable 'native' or 'websocket'."
                    .to_string(),
            }),
        }
    }

    /// Connect using the given transport implementation.
    pub(crate) async fn connect_with_transport<T: TransportProtocol + 'static>(
        params: ConnectionParams,
        mut transport: T,
    ) -> Result<Self, ConnectionError> {
        // Convert ConnectionParams to TransportConnectionParams
        let mut transport_params = TransportConnectionParams::new(params.host.clone(), params.port)
            .with_tls(params.use_tls)
            .with_validate_server_certificate(params.validate_server_certificate)
            .with_timeout(params.connection_timeout.as_millis() as u64);
        if let Some(ref fp) = params.certificate_fingerprint {
            transport_params = transport_params.with_certificate_fingerprint(fp.clone());
        }

        // Connect
        transport.connect(&transport_params).await.map_err(|e| {
            ConnectionError::ConnectionFailed {
                host: params.host.clone(),
                port: params.port,
                message: e.to_string(),
            }
        })?;

        // Authenticate
        let credentials =
            TransportCredentials::new(params.username.clone(), params.password().to_string())
                .with_client(params.client_name.clone(), params.client_version.clone());
        let session_info = transport
            .authenticate(&credentials)
            .await
            .map_err(|e| ConnectionError::AuthenticationFailed(e.to_string()))?;

        // Forward a configured query timeout to the server so it enforces the
        // limit itself. Absent configuration, no attribute is set and the
        // server's own QUERY_TIMEOUT governs.
        if let Some(d) = params.query_timeout {
            transport
                .set_query_timeout(secs_ceil(d))
                .await
                .map_err(|e| ConnectionError::ConnectionFailed {
                    host: params.host.clone(),
                    port: params.port,
                    message: format!("failed to set query timeout: {}", e),
                })?;
        }

        // Create session config from connection params. `query_timeout` seeds
        // the applied-value baseline that `execute_statement` reconciles against.
        let session_config = SessionConfig {
            query_timeout: params.query_timeout,
            ..Default::default()
        };

        // Extract session_id once to avoid double clone
        let session_id = session_info.session_id.clone();

        // Convert SessionInfo to AuthResponseData
        let auth_response = AuthResponseData {
            session_id: session_id.clone(),
            protocol_version: session_info.protocol_version,
            release_version: session_info.release_version,
            database_name: session_info.database_name,
            product_name: session_info.product_name,
            max_data_message_size: session_info.max_data_message_size,
            max_identifier_length: 128,
            max_varchar_length: 2_000_000,
            identifier_quote_string: "\"".to_string(),
            time_zone: session_info.time_zone.unwrap_or_else(|| "UTC".to_string()),
            time_zone_behavior: "INVALID TIMESTAMP TO DOUBLE".to_string(),
        };

        // Create session
        let session = SessionInfo::new(session_id, auth_response, session_config);

        let schema = params.schema.clone();

        let mut connection = Self {
            transport: Arc::new(Mutex::new(transport)),
            session,
            params,
        };

        // The schema must exist: every rejection fails the connect, and the
        // server's error text is never inspected to decide otherwise.
        if let Some(schema_name) = schema {
            if let Err(query_err) = connection.set_schema(schema_name.as_str()).await {
                let host = connection.params.host.clone();
                let port = connection.params.port;
                // The rejection is the error worth reporting; the close only
                // keeps the authenticated session from leaking.
                let _ = connection.shutdown().await;
                return Err(ConnectionError::ConnectionFailed {
                    host,
                    port,
                    message: format!(
                        "failed to set schema '{}' from the connection parameters: {}",
                        schema_name, query_err
                    ),
                });
            }
        }

        Ok(connection)
    }

    /// Create a builder for constructing a connection.
    ///
    /// # Returns
    ///
    /// A `ConnectionBuilder` instance.
    ///
    /// # Example
    ///
    pub fn builder() -> ConnectionBuilder {
        ConnectionBuilder::new()
    }

    // ========================================================================
    // Statement Creation (synchronous - Statement is now a pure data container)
    // ========================================================================

    /// Create a new statement for executing SQL.
    ///
    /// Statement is now a pure data container. Use `execute_statement()` to execute it.
    ///
    /// # Arguments
    ///
    /// * `sql` - SQL query text
    ///
    /// # Returns
    ///
    /// A `Statement` instance ready for execution via `execute_statement()`.
    ///
    /// # Example
    ///
    pub fn create_statement(&self, sql: impl Into<String>) -> Statement {
        let mut stmt = Statement::new(sql);
        if let Some(d) = self.params.query_timeout {
            stmt.set_timeout(d.as_millis().min(u64::MAX as u128) as u64);
        }
        stmt
    }

    // ========================================================================
    // Statement Execution Methods
    // ========================================================================

    /// Execute a statement and return results.
    ///
    /// # Arguments
    ///
    /// * `stmt` - Statement to execute
    ///
    /// # Returns
    ///
    /// A `ResultSet` containing the query results.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if execution fails or times out.
    ///
    /// # Example
    ///
    pub async fn execute_statement(&mut self, stmt: &Statement) -> Result<ResultSet, QueryError> {
        // Validate session state
        self.session
            .validate_ready()
            .await
            .map_err(|e| QueryError::InvalidState(e.to_string()))?;

        // Increment query counter
        self.session.increment_query_count();

        // Build final SQL with parameters
        let final_sql = stmt.build_sql()?;

        // Reconcile the session `queryTimeout` in both directions before
        // executing. `queryTimeout` is session-level, so a per-statement value
        // (or its absence) is pushed to the server whenever it differs from the
        // currently-applied value. A statement with no timeout resets the server
        // to `0` (unlimited) so it never inherits a prior statement's limit.
        let target_secs = match stmt.timeout_ms() {
            Some(ms) => secs_ceil(Duration::from_millis(ms)),
            None => 0,
        };
        let applied_secs = match self.session.config().query_timeout {
            Some(d) => secs_ceil(d),
            None => 0,
        };
        let needs_reconcile = target_secs != applied_secs;

        let mut transport_guard = self.transport.lock().await;
        if needs_reconcile {
            transport_guard
                .set_query_timeout(target_secs)
                .await
                .map_err(|e| QueryError::ExecutionFailed(e.to_string()))?;
        }
        let exec_result = transport_guard.execute_query(&final_sql).await;
        drop(transport_guard);

        // Record what was applied to the server so the next statement
        // reconciles against the correct baseline. This runs even when the
        // query itself aborts: the server's `queryTimeout` was still changed.
        if needs_reconcile {
            self.session.config_mut().query_timeout = stmt.timeout_ms().map(Duration::from_millis);
        }

        // Report the effective timeout actually enforced by the server
        // (`target_secs`, in ms) rather than the raw sub-second request —
        // e.g. a 1500ms request rounds up to a 2000ms server-side limit, and
        // that's the value that fired.
        let result =
            exec_result.map_err(|e| map_execution_error(e, target_secs.saturating_mul(1000)))?;

        // Convert transport result to ResultSet
        ResultSet::from_transport_result(result, Arc::clone(&self.transport))
    }

    /// Execute a statement and return the row count (for non-SELECT statements).
    ///
    /// # Arguments
    ///
    /// * `stmt` - Statement to execute
    ///
    /// # Returns
    ///
    /// The number of rows affected.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if execution fails or if statement is a SELECT.
    ///
    /// # Example
    ///
    pub async fn execute_statement_update(&mut self, stmt: &Statement) -> Result<i64, QueryError> {
        let result_set = self.execute_statement(stmt).await?;

        result_set.row_count().ok_or_else(|| {
            QueryError::NoResultSet("Expected row count, got result set".to_string())
        })
    }

    // ========================================================================
    // Prepared Statement Methods
    // ========================================================================

    /// Create a prepared statement for parameterized query execution.
    ///
    /// This creates a server-side prepared statement that can be executed
    /// multiple times with different parameter values.
    ///
    /// # Arguments
    ///
    /// * `sql` - SQL statement with parameter placeholders (?)
    ///
    /// # Returns
    ///
    /// A `PreparedStatement` ready for parameter binding and execution.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if preparation fails.
    ///
    /// # Example
    ///
    pub async fn prepare(
        &mut self,
        sql: impl Into<String>,
    ) -> Result<PreparedStatement, QueryError> {
        let sql = sql.into();

        // Validate session state
        self.session
            .validate_ready()
            .await
            .map_err(|e| QueryError::InvalidState(e.to_string()))?;

        let mut transport = self.transport.lock().await;
        let handle = transport
            .create_prepared_statement(&sql)
            .await
            .map_err(|e| QueryError::ExecutionFailed(e.to_string()))?;

        Ok(PreparedStatement::new(handle))
    }

    /// Execute a prepared statement and return results.
    ///
    /// # Arguments
    ///
    /// * `stmt` - Prepared statement to execute
    ///
    /// # Returns
    ///
    /// A `ResultSet` containing the query results.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if execution fails.
    ///
    /// # Example
    ///
    pub async fn execute_prepared(
        &mut self,
        stmt: &PreparedStatement,
    ) -> Result<ResultSet, QueryError> {
        if stmt.is_closed() {
            return Err(QueryError::StatementClosed);
        }

        // Validate session state
        self.session
            .validate_ready()
            .await
            .map_err(|e| QueryError::InvalidState(e.to_string()))?;

        // Increment query counter
        self.session.increment_query_count();

        // Convert parameters to column-major JSON format
        let params_data = stmt.build_parameters_data()?;

        let mut transport = self.transport.lock().await;
        let result = transport
            .execute_prepared_statement(stmt.handle_ref(), params_data)
            .await
            .map_err(|e| QueryError::ExecutionFailed(e.to_string()))?;

        drop(transport);

        ResultSet::from_transport_result(result, Arc::clone(&self.transport))
    }

    /// Execute a prepared statement and return the number of affected rows.
    ///
    /// Use this for INSERT, UPDATE, DELETE statements.
    ///
    /// # Arguments
    ///
    /// * `stmt` - Prepared statement to execute
    ///
    /// # Returns
    ///
    /// The number of rows affected.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if execution fails or statement returns a result set.
    pub async fn execute_prepared_update(
        &mut self,
        stmt: &PreparedStatement,
    ) -> Result<i64, QueryError> {
        if stmt.is_closed() {
            return Err(QueryError::StatementClosed);
        }

        // Validate session state
        self.session
            .validate_ready()
            .await
            .map_err(|e| QueryError::InvalidState(e.to_string()))?;

        // Convert parameters to column-major JSON format
        let params_data = stmt.build_parameters_data()?;

        let mut transport = self.transport.lock().await;
        let result = transport
            .execute_prepared_statement(stmt.handle_ref(), params_data)
            .await
            .map_err(|e| QueryError::ExecutionFailed(e.to_string()))?;

        drop(transport);

        match result {
            QueryResult::RowCount { count } => Ok(count),
            QueryResult::ResultSet { .. } => Err(QueryError::UnexpectedResultSet),
        }
    }

    /// Execute a prepared statement with multiple rows of parameters and return the number of
    /// affected rows.
    ///
    /// Use this for batch INSERT, UPDATE, or DELETE statements.
    ///
    /// # Arguments
    ///
    /// * `stmt` - Prepared statement to execute
    /// * `rows` - Slice of parameter rows; each row is a `Vec<Parameter>` in positional order
    ///
    /// # Returns
    ///
    /// The total number of rows affected.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if execution fails, if the statement is closed, or if Exasol
    /// returns a result set instead of an affected-row count.
    pub async fn execute_batch_update(
        &mut self,
        stmt: &PreparedStatement,
        rows: &[Vec<Parameter>],
    ) -> Result<i64, QueryError> {
        if stmt.is_closed() {
            return Err(QueryError::StatementClosed);
        }

        // Validate session state
        self.session
            .validate_ready()
            .await
            .map_err(|e| QueryError::InvalidState(e.to_string()))?;

        // Convert batch parameters to column-major JSON format
        let params_data = stmt.build_batch_parameters_data(rows)?;

        let mut transport = self.transport.lock().await;
        let result = transport
            .execute_prepared_statement(stmt.handle_ref(), params_data)
            .await
            .map_err(|e| QueryError::ExecutionFailed(e.to_string()))?;

        drop(transport);

        match result {
            QueryResult::RowCount { count } => Ok(count),
            QueryResult::ResultSet { .. } => Err(QueryError::UnexpectedResultSet),
        }
    }

    /// Execute a prepared statement with multiple rows of parameters and return a result set.
    ///
    /// Use this for batch SELECT statements or queries that return rows.
    ///
    /// # Arguments
    ///
    /// * `stmt` - Prepared statement to execute
    /// * `rows` - Slice of parameter rows; each row is a `Vec<Parameter>` in positional order
    ///
    /// # Returns
    ///
    /// A `ResultSet` containing the query results.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if execution fails or if the statement is closed.
    pub async fn execute_batch(
        &mut self,
        stmt: &PreparedStatement,
        rows: &[Vec<Parameter>],
    ) -> Result<ResultSet, QueryError> {
        if stmt.is_closed() {
            return Err(QueryError::StatementClosed);
        }

        // Validate session state
        self.session
            .validate_ready()
            .await
            .map_err(|e| QueryError::InvalidState(e.to_string()))?;

        // Increment query counter
        self.session.increment_query_count();

        // Convert batch parameters to column-major JSON format
        let params_data = stmt.build_batch_parameters_data(rows)?;

        let mut transport = self.transport.lock().await;
        let result = transport
            .execute_prepared_statement(stmt.handle_ref(), params_data)
            .await
            .map_err(|e| QueryError::ExecutionFailed(e.to_string()))?;

        drop(transport);

        ResultSet::from_transport_result(result, Arc::clone(&self.transport))
    }

    /// Close a prepared statement and release server-side resources.
    ///
    /// # Arguments
    ///
    /// * `stmt` - Prepared statement to close (consumed)
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if closing fails.
    ///
    /// # Example
    ///
    pub async fn close_prepared(&mut self, mut stmt: PreparedStatement) -> Result<(), QueryError> {
        if stmt.is_closed() {
            return Ok(());
        }

        let mut transport = self.transport.lock().await;
        transport
            .close_prepared_statement(stmt.handle_ref())
            .await
            .map_err(|e| QueryError::ExecutionFailed(e.to_string()))?;

        stmt.mark_closed();
        Ok(())
    }

    // ========================================================================
    // Convenience Methods (these internally use execute_statement)
    // ========================================================================

    /// Execute a SQL query and return results.
    ///
    /// This is a convenience method that creates a statement and executes it.
    ///
    /// # Arguments
    ///
    /// * `sql` - SQL query text
    ///
    /// # Returns
    ///
    /// A `ResultSet` containing the query results.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if execution fails.
    ///
    /// # Example
    ///
    pub async fn execute(&mut self, sql: impl Into<String>) -> Result<ResultSet, QueryError> {
        let stmt = self.create_statement(sql);
        self.execute_statement(&stmt).await
    }

    /// Execute a SQL query and return all results as RecordBatches.
    ///
    /// This is a convenience method that fetches all results into memory.
    ///
    /// # Arguments
    ///
    /// * `sql` - SQL query text
    ///
    /// # Returns
    ///
    /// A vector of `RecordBatch` instances.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if execution fails.
    ///
    /// # Example
    ///
    pub async fn query(&mut self, sql: impl Into<String>) -> Result<Vec<RecordBatch>, QueryError> {
        let result_set = self.execute(sql).await?;
        result_set.fetch_all().await
    }

    /// Execute a non-SELECT statement and return the row count.
    ///
    /// # Arguments
    ///
    /// * `sql` - SQL statement (INSERT, UPDATE, DELETE, etc.)
    ///
    /// # Returns
    ///
    /// The number of rows affected.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if execution fails.
    ///
    /// # Example
    ///
    pub async fn execute_update(&mut self, sql: impl Into<String>) -> Result<i64, QueryError> {
        let stmt = self.create_statement(sql);
        self.execute_statement_update(&stmt).await
    }

    // ========================================================================
    // Transaction Methods
    // ========================================================================

    /// Turns autocommit off on the server and marks the session as in a transaction.
    ///
    /// A `Closing` or `Closed` session ("Connection is closed") and an already
    /// active transaction ("Transaction already active") are rejected before
    /// any server request, so the server's autocommit setting stays unchanged.
    ///
    /// # Errors
    ///
    /// Returns `QueryError::TransactionError` for both rejections and when the
    /// autocommit request fails.
    pub async fn begin_transaction(&mut self) -> Result<(), QueryError> {
        // Reject before any request: autocommit must not change on the server
        // for a transaction that cannot start.
        self.session
            .ensure_can_begin_transaction()
            .await
            .map_err(|e| QueryError::TransactionError(e.to_string()))?;

        // Disable autocommit on the server so statements don't auto-commit
        self.transport
            .lock()
            .await
            .set_autocommit(false)
            .await
            .map_err(|e| QueryError::TransactionError(e.to_string()))?;

        self.session
            .begin_transaction()
            .await
            .map_err(|e| QueryError::TransactionError(e.to_string()))?;

        Ok(())
    }

    pub async fn commit(&mut self) -> Result<(), QueryError> {
        if !self.in_transaction() {
            return Ok(());
        }

        self.execute_update("COMMIT").await?;

        self.session
            .commit_transaction()
            .await
            .map_err(|e| QueryError::TransactionError(e.to_string()))?;

        Ok(())
    }

    pub async fn rollback(&mut self) -> Result<(), QueryError> {
        if !self.in_transaction() {
            return Ok(());
        }

        self.execute_update("ROLLBACK").await?;

        self.session
            .rollback_transaction()
            .await
            .map_err(|e| QueryError::TransactionError(e.to_string()))?;

        Ok(())
    }

    /// Check if a transaction is currently active.
    ///
    /// # Returns
    ///
    /// `true` if a transaction is active, `false` otherwise.
    pub fn in_transaction(&self) -> bool {
        self.session.in_transaction()
    }

    // ========================================================================
    // Session and Schema Methods
    // ========================================================================

    /// The session's current schema as the server last reported it.
    ///
    /// Reads the value the transport recorded from the server's responses,
    /// without a server request. It follows the URI schema, `set_schema`, and
    /// `OPEN SCHEMA`, `CREATE SCHEMA`, `CLOSE SCHEMA`, or `DROP SCHEMA` run as
    /// SQL, and holds the name the server opened, which can differ from the
    /// requested text (`my_schema` opens `MY_SCHEMA`).
    ///
    /// # Returns
    ///
    /// The current schema name, or `None` if the session has no current schema.
    pub async fn current_schema(&self) -> Option<String> {
        self.transport.lock().await.current_schema()
    }

    /// Set the session's current schema.
    ///
    /// Sends the name as the current-schema session attribute, never as an
    /// `OPEN SCHEMA` statement, so the name needs no quoting. The server opens
    /// the schema whose name matches exactly, otherwise the one that matches
    /// the upper-case form, and [`current_schema`](Self::current_schema) then
    /// reports the name the server opened.
    ///
    /// # Arguments
    ///
    /// * `schema` - The schema name to set
    ///
    /// # Errors
    ///
    /// Returns `QueryError::InvalidState` when the session cannot run
    /// operations, and `QueryError::ExecutionFailed` with the server's message
    /// when the server rejects the schema, in which case the current schema
    /// stays unchanged.
    pub async fn set_schema(&mut self, schema: impl Into<String>) -> Result<(), QueryError> {
        self.session
            .validate_ready()
            .await
            .map_err(|e| QueryError::InvalidState(e.to_string()))?;

        self.transport
            .lock()
            .await
            .set_current_schema(&schema.into())
            .await
            .map_err(|e| QueryError::ExecutionFailed(e.to_string()))
    }

    /// Ask the server for the session's current schema with a get-attributes
    /// request.
    ///
    /// Serves the ADBC `adbc.connection.db_schema` read, which reports the
    /// server's value rather than the recorded one, so it also sees a change
    /// no response of this session reported.
    #[cfg(any(feature = "ffi", test))]
    pub(crate) async fn refresh_current_schema(&self) -> Result<Option<String>, QueryError> {
        self.session
            .validate_ready()
            .await
            .map_err(|e| QueryError::InvalidState(e.to_string()))?;

        self.transport
            .lock()
            .await
            .refresh_current_schema()
            .await
            .map_err(|e| QueryError::ExecutionFailed(e.to_string()))
    }

    // ========================================================================
    // Metadata Methods
    // ========================================================================

    /// Get metadata about catalogs.
    ///
    /// # Returns
    ///
    /// A `ResultSet` containing catalog metadata.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if the operation fails.
    pub async fn get_catalogs(&mut self) -> Result<ResultSet, QueryError> {
        self.execute("SELECT DISTINCT SCHEMA_NAME AS CATALOG_NAME FROM SYS.EXA_ALL_SCHEMAS ORDER BY CATALOG_NAME")
            .await
    }

    /// Get metadata about schemas.
    ///
    /// # Arguments
    ///
    /// * `catalog` - Optional catalog name filter
    ///
    /// # Returns
    ///
    /// A `ResultSet` containing schema metadata.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if the operation fails.
    pub async fn get_schemas(&mut self, catalog: Option<&str>) -> Result<ResultSet, QueryError> {
        let sql = if let Some(cat) = catalog {
            format!(
                "SELECT SCHEMA_NAME FROM SYS.EXA_ALL_SCHEMAS WHERE SCHEMA_NAME = '{}' ORDER BY SCHEMA_NAME",
                cat.replace('\'', "''")
            )
        } else {
            "SELECT SCHEMA_NAME FROM SYS.EXA_ALL_SCHEMAS ORDER BY SCHEMA_NAME".to_string()
        };
        self.execute(sql).await
    }

    /// Get metadata about tables.
    ///
    /// # Arguments
    ///
    /// * `catalog` - Optional catalog name filter
    /// * `schema` - Optional schema name filter
    /// * `table` - Optional table name filter
    ///
    /// # Returns
    ///
    /// A `ResultSet` containing table metadata.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if the operation fails.
    pub async fn get_tables(
        &mut self,
        catalog: Option<&str>,
        schema: Option<&str>,
        table: Option<&str>,
    ) -> Result<ResultSet, QueryError> {
        let mut conditions = vec!["OBJECT_TYPE IN ('TABLE', 'VIEW')".to_string()];

        // Exasol has no catalogs — ignore the catalog parameter
        let _ = catalog;
        if let Some(sch) = schema {
            conditions.push(format!("ROOT_NAME = '{}'", sch.replace('\'', "''")));
        }
        if let Some(tbl) = table {
            conditions.push(format!("OBJECT_NAME = '{}'", tbl.replace('\'', "''")));
        }

        let where_clause = format!("WHERE {}", conditions.join(" AND "));

        let sql = format!(
            "SELECT ROOT_NAME AS TABLE_SCHEMA, OBJECT_NAME AS TABLE_NAME, OBJECT_TYPE AS TABLE_TYPE FROM SYS.EXA_ALL_OBJECTS {} ORDER BY ROOT_NAME, OBJECT_NAME",
            where_clause
        );

        self.execute(sql).await
    }

    /// Get metadata about columns.
    ///
    /// # Arguments
    ///
    /// * `catalog` - Optional catalog name filter
    /// * `schema` - Optional schema name filter
    /// * `table` - Optional table name filter
    /// * `column` - Optional column name filter
    ///
    /// # Returns
    ///
    /// A `ResultSet` containing column metadata.
    ///
    /// # Errors
    ///
    /// Returns `QueryError` if the operation fails.
    pub async fn get_columns(
        &mut self,
        catalog: Option<&str>,
        schema: Option<&str>,
        table: Option<&str>,
        column: Option<&str>,
    ) -> Result<ResultSet, QueryError> {
        let mut conditions = Vec::new();

        if let Some(cat) = catalog {
            conditions.push(format!("COLUMN_SCHEMA = '{}'", cat.replace('\'', "''")));
        }
        if let Some(sch) = schema {
            conditions.push(format!("COLUMN_SCHEMA = '{}'", sch.replace('\'', "''")));
        }
        if let Some(tbl) = table {
            conditions.push(format!("COLUMN_TABLE = '{}'", tbl.replace('\'', "''")));
        }
        if let Some(col) = column {
            conditions.push(format!("COLUMN_NAME = '{}'", col.replace('\'', "''")));
        }

        let where_clause = if conditions.is_empty() {
            String::new()
        } else {
            format!("WHERE {}", conditions.join(" AND "))
        };

        let sql = format!(
            "SELECT COLUMN_SCHEMA, COLUMN_TABLE, COLUMN_NAME, COLUMN_TYPE, COLUMN_NUM_PREC, COLUMN_NUM_SCALE, COLUMN_IS_NULLABLE \
             FROM SYS.EXA_ALL_COLUMNS {} ORDER BY COLUMN_SCHEMA, COLUMN_TABLE, ORDINAL_POSITION",
            where_clause
        );

        self.execute(sql).await
    }

    // ========================================================================
    // Session Information Methods
    // ========================================================================

    /// Get session information.
    ///
    /// # Returns
    ///
    /// The session ID.
    pub fn session_id(&self) -> &str {
        self.session.session_id()
    }

    /// Get connection parameters.
    ///
    /// # Returns
    ///
    /// A reference to the connection parameters.
    pub fn params(&self) -> &ConnectionParams {
        &self.params
    }

    /// Check if the connection is closed.
    ///
    /// Reports closed when either the session has been closed or the transport
    /// has been terminated. A terminating export timeout
    /// (`ExportError::Timeout { transport_terminated: true }`) is what makes the
    /// transport half of this check fire even while the session still believes
    /// it is open.
    ///
    /// # Returns
    ///
    /// `true` if the connection is closed, `false` otherwise.
    pub async fn is_closed(&self) -> bool {
        self.session.is_closed().await || !self.transport.lock().await.is_connected()
    }

    /// Close the connection.
    ///
    /// This closes the session and transport layer.
    ///
    /// # Errors
    ///
    /// Returns `ConnectionError` if closing fails.
    ///
    /// # Example
    ///
    pub async fn close(self) -> Result<(), ConnectionError> {
        // Close session
        self.session.close().await?;

        // Close transport
        let mut transport = self.transport.lock().await;
        transport
            .close()
            .await
            .map_err(|e| ConnectionError::ConnectionFailed {
                host: self.params.host.clone(),
                port: self.params.port,
                message: e.to_string(),
            })?;

        Ok(())
    }

    /// Shut down the connection without consuming self.
    ///
    /// Unlike `close()`, this can be called through a shared reference,
    /// making it suitable for use in `Drop` implementations where ownership
    /// transfer is not possible (e.g., when the connection is behind `Arc<Mutex<>>`).
    pub async fn shutdown(&self) -> Result<(), ConnectionError> {
        self.session.close().await?;

        let mut transport = self.transport.lock().await;
        transport
            .close()
            .await
            .map_err(|e| ConnectionError::ConnectionFailed {
                host: self.params.host.clone(),
                port: self.params.port,
                message: e.to_string(),
            })?;

        Ok(())
    }

    // ========================================================================
    // Import/Export Methods
    // ========================================================================

    /// Creates an SQL executor closure for import/export operations.
    ///
    /// This is a helper method that creates a closure which can execute SQL
    /// statements and return the row count. The closure captures a cloned
    /// reference to the transport, allowing it to be called multiple times
    /// (e.g., for parallel file imports).
    ///
    /// # Returns
    ///
    /// A closure that takes an SQL string and returns a Future resolving to
    /// either the affected row count or an error string.
    fn make_sql_executor(
        &self,
    ) -> impl Fn(
        String,
    )
        -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<u64, String>> + Send>> {
        let transport = Arc::clone(&self.transport);
        move |sql: String| {
            let transport = Arc::clone(&transport);
            Box::pin(async move {
                let mut transport_guard = transport.lock().await;
                match transport_guard.execute_query(&sql).await {
                    Ok(QueryResult::RowCount { count }) => Ok(count as u64),
                    Ok(QueryResult::ResultSet { .. }) => Ok(0),
                    Err(e) => Err(e.to_string()),
                }
            })
        }
    }

    /// Import CSV data from a file into an Exasol table.
    ///
    /// This method reads CSV data from the specified file and imports it into
    /// the target table using Exasol's HTTP transport layer.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `file_path` - Path to the CSV file
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    ///
    /// # Example
    ///
    pub async fn import_csv_from_file(
        &mut self,
        table: &str,
        file_path: &std::path::Path,
        options: crate::import::csv::CsvImportOptions,
    ) -> Result<u64, crate::import::ImportError> {
        // Pass Exasol host/port from connection params to import options
        let options = options
            .exasol_host(&self.params.host)
            .exasol_port(self.params.port);

        crate::import::csv::import_from_file(self.make_sql_executor(), table, file_path, options)
            .await
    }

    /// Import CSV data from an async reader into an Exasol table.
    ///
    /// This method reads CSV data from an async reader and imports it into
    /// the target table using Exasol's HTTP transport layer.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `reader` - Async reader providing CSV data
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    pub async fn import_csv_from_stream<R>(
        &mut self,
        table: &str,
        reader: R,
        options: crate::import::csv::CsvImportOptions,
    ) -> Result<u64, crate::import::ImportError>
    where
        R: tokio::io::AsyncRead + Unpin + Send + 'static,
    {
        // Pass Exasol host/port from connection params to import options
        let options = options
            .exasol_host(&self.params.host)
            .exasol_port(self.params.port);

        crate::import::csv::import_from_stream(self.make_sql_executor(), table, reader, options)
            .await
    }

    /// Import CSV data from an iterator into an Exasol table.
    ///
    /// This method converts iterator rows to CSV format and imports them into
    /// the target table using Exasol's HTTP transport layer.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `rows` - Iterator of rows, where each row is an iterator of field values
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    ///
    /// # Example
    ///
    pub async fn import_csv_from_iter<I, T, S>(
        &mut self,
        table: &str,
        rows: I,
        options: crate::import::csv::CsvImportOptions,
    ) -> Result<u64, crate::import::ImportError>
    where
        I: IntoIterator<Item = T> + Send + 'static,
        T: IntoIterator<Item = S> + Send,
        S: AsRef<str>,
    {
        // Pass Exasol host/port from connection params to import options
        let options = options
            .exasol_host(&self.params.host)
            .exasol_port(self.params.port);

        crate::import::csv::import_from_iter(self.make_sql_executor(), table, rows, options).await
    }

    /// Export data from an Exasol table or query to a CSV file.
    ///
    /// This method exports data from the specified source to a CSV file
    /// using Exasol's HTTP transport layer.
    ///
    /// # Arguments
    ///
    /// * `source` - The data source (table or query)
    /// * `file_path` - Path to the output file
    /// * `options` - Export options
    ///
    /// # Returns
    ///
    /// The number of rows exported on success.
    ///
    /// # Errors
    ///
    /// Returns `ExportError` if the export fails.
    ///
    /// # Example
    ///
    pub async fn export_csv_to_file(
        &mut self,
        source: crate::query::export::ExportSource,
        file_path: &std::path::Path,
        options: crate::export::csv::CsvExportOptions,
    ) -> Result<u64, crate::export::csv::ExportError> {
        // Pass Exasol host/port from connection params to export options
        let options = options
            .exasol_host(&self.params.host)
            .exasol_port(self.params.port);

        let mut transport_guard = self.transport.lock().await;
        crate::export::csv::export_to_file(&mut *transport_guard, source, file_path, options).await
    }

    /// Export data from an Exasol table or query to an async writer.
    ///
    /// This method exports data from the specified source to an async writer
    /// using Exasol's HTTP transport layer.
    ///
    /// # Arguments
    ///
    /// * `source` - The data source (table or query)
    /// * `writer` - Async writer to write the CSV data to
    /// * `options` - Export options
    ///
    /// # Returns
    ///
    /// The number of rows exported on success.
    ///
    /// # Errors
    ///
    /// Returns `ExportError` if the export fails.
    pub async fn export_csv_to_stream<W>(
        &mut self,
        source: crate::query::export::ExportSource,
        writer: W,
        options: crate::export::csv::CsvExportOptions,
    ) -> Result<u64, crate::export::csv::ExportError>
    where
        W: tokio::io::AsyncWrite + Unpin,
    {
        // Pass Exasol host/port from connection params to export options
        let options = options
            .exasol_host(&self.params.host)
            .exasol_port(self.params.port);

        let mut transport_guard = self.transport.lock().await;
        crate::export::csv::export_to_stream(&mut *transport_guard, source, writer, options).await
    }

    /// Export data from an Exasol table or query to an in-memory list of rows.
    ///
    /// Each row is represented as a vector of string values.
    ///
    /// # Arguments
    ///
    /// * `source` - The data source (table or query)
    /// * `options` - Export options
    ///
    /// # Returns
    ///
    /// A vector of rows, where each row is a vector of column values.
    ///
    /// # Errors
    ///
    /// Returns `ExportError` if the export fails.
    ///
    /// # Example
    ///
    pub async fn export_csv_to_list(
        &mut self,
        source: crate::query::export::ExportSource,
        options: crate::export::csv::CsvExportOptions,
    ) -> Result<Vec<Vec<String>>, crate::export::csv::ExportError> {
        // Pass Exasol host/port from connection params to export options
        let options = options
            .exasol_host(&self.params.host)
            .exasol_port(self.params.port);

        let mut transport_guard = self.transport.lock().await;
        crate::export::csv::export_to_list(&mut *transport_guard, source, options).await
    }

    /// Import multiple CSV files in parallel into an Exasol table.
    ///
    /// This method reads CSV data from multiple files and imports them into
    /// the target table using parallel HTTP transport connections. Each file
    /// gets its own connection with a unique internal address.
    ///
    /// For a single file, this method delegates to `import_csv_from_file`.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `paths` - File paths (accepts single path, Vec, array, or slice)
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails. Uses fail-fast semantics.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use exarrow_rs::adbc::Connection;
    /// use exarrow_rs::import::CsvImportOptions;
    /// use std::path::PathBuf;
    ///
    /// # async fn example(conn: &mut Connection) -> Result<(), Box<dyn std::error::Error>> {
    /// let files = vec![
    ///     PathBuf::from("/data/part1.csv"),
    ///     PathBuf::from("/data/part2.csv"),
    /// ];
    ///
    /// let options = CsvImportOptions::default();
    /// let rows = conn.import_csv_from_files("my_table", files, options).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn import_csv_from_files<S: crate::import::IntoFileSources>(
        &mut self,
        table: &str,
        paths: S,
        options: crate::import::csv::CsvImportOptions,
    ) -> Result<u64, crate::import::ImportError> {
        // Pass Exasol host/port from connection params to import options
        let options = options
            .exasol_host(&self.params.host)
            .exasol_port(self.params.port);

        crate::import::csv::import_from_files(self.make_sql_executor(), table, paths, options).await
    }

    /// Whether the connected Exasol server supports native Parquet IMPORT.
    ///
    /// Returns `true` when the server version is at least 2025.1.11, which
    /// introduced the `FROM PARQUET` clause. The result is memoized for the
    /// session lifetime.
    pub fn supports_native_parquet_import(&self) -> bool {
        self.session.supports_native_parquet_import()
    }

    /// Resolve whether to use the native Parquet import path for a given request.
    ///
    /// The `native_parquet_override` field on `options` takes precedence: if it
    /// is `Some(b)`, that value is used directly. Otherwise the result of
    /// `supports_native_parquet_import()` is returned.
    fn resolve_native_parquet(
        &self,
        options: &crate::import::parquet::ParquetImportOptions,
    ) -> bool {
        options
            .native_parquet_override
            .unwrap_or_else(|| self.supports_native_parquet_import())
    }

    /// Import data from a Parquet file into an Exasol table.
    ///
    /// This method reads a Parquet file, converts the data to CSV format,
    /// and imports it into the target table using Exasol's HTTP transport layer.
    /// When the connected server supports native Parquet import (Exasol 2025.1.11+),
    /// the raw Parquet bytes are streamed directly without CSV conversion.
    /// On that native path, the driver opens the file and reads each range that
    /// Exasol requests in pieces of at most 64 KiB, so memory does not grow with
    /// the file size. The file must stay unchanged until the import ends, and a
    /// file that becomes shorter fails the import.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `file_path` - Path to the Parquet file
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    ///
    /// # Example
    ///
    pub async fn import_from_parquet(
        &mut self,
        table: &str,
        file_path: &std::path::Path,
        options: crate::import::parquet::ParquetImportOptions,
    ) -> Result<u64, crate::import::ImportError> {
        // Pass Exasol host/port from connection params to import options
        let options = options
            .with_exasol_host(&self.params.host)
            .with_exasol_port(self.params.port);

        let use_native = self.resolve_native_parquet(&options);

        crate::import::parquet::import_from_parquet(
            self.make_sql_executor(),
            table,
            file_path,
            options,
            use_native,
        )
        .await
    }

    /// Import Parquet data from an async reader into an Exasol table.
    ///
    /// This method reads Parquet data from an async reader and imports it into
    /// the target table. It buffers the whole stream in memory on both import
    /// paths, because Parquet keeps its metadata at the end of the file.
    ///
    /// When the connected server supports native Parquet import (Exasol 2025.1.11+),
    /// the buffered bytes are forwarded directly without CSV conversion.
    ///
    /// # Bounding memory
    ///
    /// To bound memory, import from a file path with
    /// [`import_from_parquet`](Self::import_from_parquet), which streams the
    /// file instead of buffering it. Or decode the Parquet data yourself and
    /// pass the RecordBatches in groups to
    /// [`import_from_record_batches`](Self::import_from_record_batches). Each
    /// call is one IMPORT statement and holds the CSV of its own batches more
    /// than once. Each call commits separately unless autocommit is off, so a
    /// failure in a later group leaves the earlier groups in the table.
    /// [`import_from_arrow_ipc`](Self::import_from_arrow_ipc) also reads its
    /// whole input.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `reader` - Async reader providing Parquet data
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    pub async fn import_from_parquet_stream<R>(
        &mut self,
        table: &str,
        reader: R,
        options: crate::import::parquet::ParquetImportOptions,
    ) -> Result<u64, crate::import::ImportError>
    where
        R: tokio::io::AsyncRead + Unpin + Send + 'static,
    {
        let options = options
            .with_exasol_host(&self.params.host)
            .with_exasol_port(self.params.port);

        let use_native = self.resolve_native_parquet(&options);

        crate::import::parquet::import_from_parquet_stream(
            self.make_sql_executor(),
            table,
            reader,
            options,
            use_native,
        )
        .await
    }

    /// Import multiple Parquet files in parallel into an Exasol table.
    ///
    /// On the CSV conversion path, each file converts to CSV while its CSV
    /// streams through its own HTTP transport connection, so memory holds a few
    /// RecordBatches of CSV per file, not whole files. The native Parquet path
    /// opens each file and reads one 64 KiB piece at a time when Exasol requests
    /// a range, so memory does not grow with the file size. Each file must stay
    /// unchanged until the import ends, and a file that becomes shorter fails
    /// the import.
    ///
    /// For a single file, this method delegates to `import_from_parquet`.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `paths` - File paths (accepts single path, Vec, array, or slice)
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails. Uses fail-fast semantics.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use exarrow_rs::adbc::Connection;
    /// use exarrow_rs::import::ParquetImportOptions;
    /// use std::path::PathBuf;
    ///
    /// # async fn example(conn: &mut Connection) -> Result<(), Box<dyn std::error::Error>> {
    /// let files = vec![
    ///     PathBuf::from("/data/part1.parquet"),
    ///     PathBuf::from("/data/part2.parquet"),
    /// ];
    ///
    /// let options = ParquetImportOptions::default();
    /// let rows = conn.import_parquet_from_files("my_table", files, options).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn import_parquet_from_files<S: crate::import::IntoFileSources>(
        &mut self,
        table: &str,
        paths: S,
        options: crate::import::parquet::ParquetImportOptions,
    ) -> Result<u64, crate::import::ImportError> {
        // Pass Exasol host/port from connection params to import options
        let options = options
            .with_exasol_host(&self.params.host)
            .with_exasol_port(self.params.port);

        let use_native = self.resolve_native_parquet(&options);

        crate::import::parquet::import_from_parquet_files(
            self.make_sql_executor(),
            table,
            paths,
            options,
            use_native,
        )
        .await
    }

    /// Export data from an Exasol table or query to a Parquet file.
    ///
    /// The Parquet file carries the source's column names and Exasol types: the driver prepares
    /// the source's SELECT statement to read them, then converts the exported CSV to typed
    /// values. INTERVAL, GEOMETRY, and HASHTYPE columns are written as `Utf8` text, and
    /// TIMESTAMP WITH LOCAL TIME ZONE columns as timestamps without a time zone that hold the
    /// session-local value. An empty export writes a file with the schema and no rows. An empty
    /// field is NULL, so `ParquetExportOptions::null_value` has no effect here. Typed values
    /// need Exasol's default session formats for numbers, dates, and timestamps.
    ///
    /// # Arguments
    ///
    /// * `source` - The data source (table or query); it must produce a result set
    /// * `file_path` - Path to the output Parquet file; it is created only when the export
    ///   succeeds
    /// * `options` - Export options
    ///
    /// # Returns
    ///
    /// The number of rows exported on success.
    ///
    /// # Errors
    ///
    /// Returns `ExportError::SqlExecutionError` when the source cannot be prepared, produces no
    /// result set, or has a column type with no Arrow mapping. Returns
    /// `ExportError::CsvParseError` when a value does not match its column type, and also, with
    /// row 0, when the Parquet writer fails. Returns `ExportError::IoError` when the output file
    /// cannot be created, and `ExportError::TransportError` or another variant for transport
    /// failures.
    ///
    /// # Example
    ///
    pub async fn export_to_parquet(
        &mut self,
        source: crate::query::export::ExportSource,
        file_path: &std::path::Path,
        options: crate::export::parquet::ParquetExportOptions,
    ) -> Result<u64, crate::export::csv::ExportError> {
        // Pass Exasol host/port from connection params to export options
        let options = options
            .exasol_host(&self.params.host)
            .exasol_port(self.params.port);

        let mut transport_guard = self.transport.lock().await;
        crate::export::parquet::export_to_parquet_via_transport(
            &mut *transport_guard,
            source,
            file_path,
            options,
        )
        .await
    }

    /// Import data from an Arrow RecordBatch into an Exasol table.
    ///
    /// This method converts the RecordBatch to CSV format and imports it
    /// into the target table using Exasol's HTTP transport layer.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `batch` - The RecordBatch to import
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    ///
    /// # Example
    ///
    pub async fn import_from_record_batch(
        &mut self,
        table: &str,
        batch: &RecordBatch,
        options: crate::import::arrow::ArrowImportOptions,
    ) -> Result<u64, crate::import::ImportError> {
        // Pass Exasol host/port from connection params to import options
        let options = options
            .exasol_host(&self.params.host)
            .exasol_port(self.params.port);

        crate::import::arrow::import_from_record_batch(
            self.make_sql_executor(),
            table,
            batch,
            options,
        )
        .await
    }

    /// Import data from multiple Arrow RecordBatches into an Exasol table.
    ///
    /// This method converts each RecordBatch to CSV format and imports them
    /// into the target table using Exasol's HTTP transport layer.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `batches` - An iterator of RecordBatches to import
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    pub async fn import_from_record_batches<I>(
        &mut self,
        table: &str,
        batches: I,
        options: crate::import::arrow::ArrowImportOptions,
    ) -> Result<u64, crate::import::ImportError>
    where
        I: IntoIterator<Item = RecordBatch>,
    {
        // Pass Exasol host/port from connection params to import options
        let options = options
            .exasol_host(&self.params.host)
            .exasol_port(self.params.port);

        crate::import::arrow::import_from_record_batches(
            self.make_sql_executor(),
            table,
            batches,
            options,
        )
        .await
    }

    /// Import data from an Arrow IPC file/stream into an Exasol table.
    ///
    /// This method reads Arrow IPC format data, converts it to CSV,
    /// and imports it into the target table using Exasol's HTTP transport layer.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `reader` - An async reader containing Arrow IPC data
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    ///
    /// # Example
    ///
    pub async fn import_from_arrow_ipc<R>(
        &mut self,
        table: &str,
        reader: R,
        options: crate::import::arrow::ArrowImportOptions,
    ) -> Result<u64, crate::import::ImportError>
    where
        R: tokio::io::AsyncRead + Unpin + Send,
    {
        // Pass Exasol host/port from connection params to import options
        let options = options
            .exasol_host(&self.params.host)
            .exasol_port(self.params.port);

        crate::import::arrow::import_from_arrow_ipc(
            self.make_sql_executor(),
            table,
            reader,
            options,
        )
        .await
    }

    /// Export data from an Exasol table or query to Arrow RecordBatches.
    ///
    /// This method exports data from the specified source and converts it
    /// to Arrow RecordBatches.
    ///
    /// # Arguments
    ///
    /// * `source` - The data source (table or query)
    /// * `options` - Export options
    ///
    /// # Returns
    ///
    /// A vector of RecordBatches on success.
    ///
    /// # Errors
    ///
    /// Returns `ExportError` if the export fails.
    ///
    /// # Example
    ///
    pub async fn export_to_record_batches(
        &mut self,
        source: crate::query::export::ExportSource,
        options: crate::export::arrow::ArrowExportOptions,
    ) -> Result<Vec<RecordBatch>, crate::export::csv::ExportError> {
        // Pass Exasol host/port from connection params to export options
        let options = options
            .exasol_host(&self.params.host)
            .exasol_port(self.params.port);

        let mut transport_guard = self.transport.lock().await;
        crate::export::arrow::export_to_record_batches(&mut *transport_guard, source, options).await
    }

    /// Export data from an Exasol table or query to an Arrow IPC file.
    ///
    /// This method exports data from the specified source to an Arrow IPC file.
    ///
    /// # Arguments
    ///
    /// * `source` - The data source (table or query)
    /// * `file_path` - Path to the output Arrow IPC file
    /// * `options` - Export options
    ///
    /// # Returns
    ///
    /// The number of rows exported on success.
    ///
    /// # Errors
    ///
    /// Returns `ExportError` if the export fails.
    ///
    /// # Example
    ///
    pub async fn export_to_arrow_ipc(
        &mut self,
        source: crate::query::export::ExportSource,
        file_path: &std::path::Path,
        options: crate::export::arrow::ArrowExportOptions,
    ) -> Result<u64, crate::export::csv::ExportError> {
        // Pass Exasol host/port from connection params to export options
        let options = options
            .exasol_host(&self.params.host)
            .exasol_port(self.params.port);

        let mut transport_guard = self.transport.lock().await;
        crate::export::arrow::export_to_arrow_ipc(&mut *transport_guard, source, file_path, options)
            .await
    }

    // ========================================================================
    // Blocking Import/Export Methods
    // ========================================================================

    /// Import CSV data from a file into an Exasol table (blocking).
    ///
    /// This is a synchronous wrapper around [`import_csv_from_file`](Self::import_csv_from_file)
    /// for use in non-async contexts.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `file_path` - Path to the CSV file
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    ///
    /// # Example
    ///
    pub fn blocking_import_csv_from_file(
        &mut self,
        table: &str,
        file_path: &std::path::Path,
        options: crate::import::csv::CsvImportOptions,
    ) -> Result<u64, crate::import::ImportError> {
        blocking_runtime().block_on(self.import_csv_from_file(table, file_path, options))
    }

    /// Import multiple CSV files in parallel into an Exasol table (blocking).
    ///
    /// This is a synchronous wrapper around [`import_csv_from_files`](Self::import_csv_from_files)
    /// for use in non-async contexts.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `paths` - File paths (accepts single path, Vec, array, or slice)
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    pub fn blocking_import_csv_from_files<S: crate::import::IntoFileSources>(
        &mut self,
        table: &str,
        paths: S,
        options: crate::import::csv::CsvImportOptions,
    ) -> Result<u64, crate::import::ImportError> {
        blocking_runtime().block_on(self.import_csv_from_files(table, paths, options))
    }

    /// Import data from a Parquet file into an Exasol table (blocking).
    ///
    /// This is a synchronous wrapper around [`import_from_parquet`](Self::import_from_parquet)
    /// for use in non-async contexts.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `file_path` - Path to the Parquet file
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    ///
    /// # Example
    ///
    pub fn blocking_import_from_parquet(
        &mut self,
        table: &str,
        file_path: &std::path::Path,
        options: crate::import::parquet::ParquetImportOptions,
    ) -> Result<u64, crate::import::ImportError> {
        blocking_runtime().block_on(self.import_from_parquet(table, file_path, options))
    }

    /// Import Parquet data from an async reader into an Exasol table (blocking).
    ///
    /// This is a synchronous wrapper around [`import_from_parquet_stream`](Self::import_from_parquet_stream)
    /// for use in non-async contexts. It buffers the whole stream in memory on
    /// both import paths, because Parquet keeps its metadata at the end of the
    /// file.
    ///
    /// # Bounding memory
    ///
    /// To bound memory, import from a file path with
    /// [`blocking_import_from_parquet`](Self::blocking_import_from_parquet),
    /// which streams the file instead of buffering it. Or decode the Parquet
    /// data yourself and import the RecordBatches in groups with
    /// [`blocking_import_from_record_batch`](Self::blocking_import_from_record_batch),
    /// which imports one RecordBatch per call. Each call is one IMPORT
    /// statement and holds the CSV of its batch more than once. Each call
    /// commits separately unless autocommit is off, so a failure in a later
    /// call leaves the earlier calls in the table.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `reader` - Async reader providing Parquet data
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    pub fn blocking_import_from_parquet_stream<R>(
        &mut self,
        table: &str,
        reader: R,
        options: crate::import::parquet::ParquetImportOptions,
    ) -> Result<u64, crate::import::ImportError>
    where
        R: tokio::io::AsyncRead + Unpin + Send + 'static,
    {
        blocking_runtime().block_on(self.import_from_parquet_stream(table, reader, options))
    }

    /// Import multiple Parquet files in parallel into an Exasol table (blocking).
    ///
    /// This is a synchronous wrapper around [`import_parquet_from_files`](Self::import_parquet_from_files)
    /// for use in non-async contexts.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `paths` - File paths (accepts single path, Vec, array, or slice)
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    pub fn blocking_import_parquet_from_files<S: crate::import::IntoFileSources>(
        &mut self,
        table: &str,
        paths: S,
        options: crate::import::parquet::ParquetImportOptions,
    ) -> Result<u64, crate::import::ImportError> {
        blocking_runtime().block_on(self.import_parquet_from_files(table, paths, options))
    }

    /// Import data from an Arrow RecordBatch into an Exasol table (blocking).
    ///
    /// This is a synchronous wrapper around [`import_from_record_batch`](Self::import_from_record_batch)
    /// for use in non-async contexts.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `batch` - The RecordBatch to import
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    ///
    /// # Example
    ///
    pub fn blocking_import_from_record_batch(
        &mut self,
        table: &str,
        batch: &RecordBatch,
        options: crate::import::arrow::ArrowImportOptions,
    ) -> Result<u64, crate::import::ImportError> {
        blocking_runtime().block_on(self.import_from_record_batch(table, batch, options))
    }

    /// Import data from an Arrow IPC file into an Exasol table (blocking).
    ///
    /// This is a synchronous wrapper around [`import_from_arrow_ipc`](Self::import_from_arrow_ipc)
    /// for use in non-async contexts.
    ///
    /// Note: This method requires a synchronous reader that implements `std::io::Read`.
    /// The data will be read into memory before being imported.
    ///
    /// # Arguments
    ///
    /// * `table` - Name of the target table
    /// * `file_path` - Path to the Arrow IPC file
    /// * `options` - Import options
    ///
    /// # Returns
    ///
    /// The number of rows imported on success.
    ///
    /// # Errors
    ///
    /// Returns `ImportError` if the import fails.
    ///
    /// # Example
    ///
    pub fn blocking_import_from_arrow_ipc(
        &mut self,
        table: &str,
        file_path: &std::path::Path,
        options: crate::import::arrow::ArrowImportOptions,
    ) -> Result<u64, crate::import::ImportError> {
        blocking_runtime().block_on(async {
            let file = tokio::fs::File::open(file_path)
                .await
                .map_err(crate::import::ImportError::IoError)?;
            self.import_from_arrow_ipc(table, file, options).await
        })
    }

    /// Export data from an Exasol table or query to a CSV file (blocking).
    ///
    /// This is a synchronous wrapper around [`export_csv_to_file`](Self::export_csv_to_file)
    /// for use in non-async contexts.
    ///
    /// # Blocking behavior
    ///
    /// No client-side timeout is armed by default, so a stalled HTTP tunnel
    /// blocks the calling OS thread indefinitely with no cancellation path.
    /// Bound the wait with `CsvExportOptions::timeout_ms`, or with the
    /// server-enforced `query_timeout` connection parameter.
    ///
    /// # Arguments
    ///
    /// * `source` - The data source (table or query)
    /// * `file_path` - Path to the output file
    /// * `options` - Export options
    ///
    /// # Returns
    ///
    /// The number of rows exported on success.
    ///
    /// # Errors
    ///
    /// Returns `ExportError` if the export fails.
    ///
    /// # Example
    ///
    pub fn blocking_export_csv_to_file(
        &mut self,
        source: crate::query::export::ExportSource,
        file_path: &std::path::Path,
        options: crate::export::csv::CsvExportOptions,
    ) -> Result<u64, crate::export::csv::ExportError> {
        blocking_runtime().block_on(self.export_csv_to_file(source, file_path, options))
    }

    /// Export data from an Exasol table or query to a Parquet file (blocking).
    ///
    /// This is a synchronous wrapper around [`export_to_parquet`](Self::export_to_parquet)
    /// for use in non-async contexts.
    ///
    /// # Blocking behavior
    ///
    /// No client-side timeout is armed by default, so a stalled HTTP tunnel
    /// blocks the calling OS thread indefinitely with no cancellation path.
    /// `ParquetExportOptions` exposes no `timeout_ms`, so the only available
    /// bound is the server-enforced `query_timeout` connection parameter.
    ///
    /// # Arguments
    ///
    /// * `source` - The data source (table or query)
    /// * `file_path` - Path to the output Parquet file
    /// * `options` - Export options
    ///
    /// # Returns
    ///
    /// The number of rows exported on success.
    ///
    /// # Errors
    ///
    /// Returns `ExportError` if the export fails.
    ///
    /// # Example
    ///
    pub fn blocking_export_to_parquet(
        &mut self,
        source: crate::query::export::ExportSource,
        file_path: &std::path::Path,
        options: crate::export::parquet::ParquetExportOptions,
    ) -> Result<u64, crate::export::csv::ExportError> {
        blocking_runtime().block_on(self.export_to_parquet(source, file_path, options))
    }

    /// Export data from an Exasol table or query to Arrow RecordBatches (blocking).
    ///
    /// This is a synchronous wrapper around [`export_to_record_batches`](Self::export_to_record_batches)
    /// for use in non-async contexts.
    ///
    /// # Blocking behavior
    ///
    /// No client-side timeout is armed by default, so a stalled HTTP tunnel
    /// blocks the calling OS thread indefinitely with no cancellation path.
    /// `ArrowExportOptions` exposes no `timeout_ms`, so the only available
    /// bound is the server-enforced `query_timeout` connection parameter.
    ///
    /// # Arguments
    ///
    /// * `source` - The data source (table or query)
    /// * `options` - Export options
    ///
    /// # Returns
    ///
    /// A vector of RecordBatches on success.
    ///
    /// # Errors
    ///
    /// Returns `ExportError` if the export fails.
    ///
    /// # Example
    ///
    pub fn blocking_export_to_record_batches(
        &mut self,
        source: crate::query::export::ExportSource,
        options: crate::export::arrow::ArrowExportOptions,
    ) -> Result<Vec<RecordBatch>, crate::export::csv::ExportError> {
        blocking_runtime().block_on(self.export_to_record_batches(source, options))
    }

    /// Export data from an Exasol table or query to an Arrow IPC file (blocking).
    ///
    /// This is a synchronous wrapper around [`export_to_arrow_ipc`](Self::export_to_arrow_ipc)
    /// for use in non-async contexts.
    ///
    /// # Arguments
    ///
    /// * `source` - The data source (table or query)
    /// * `file_path` - Path to the output Arrow IPC file
    /// * `options` - Export options
    ///
    /// # Returns
    ///
    /// The number of rows exported on success.
    ///
    /// # Errors
    ///
    /// Returns `ExportError` if the export fails.
    ///
    /// # Example
    ///
    pub fn blocking_export_to_arrow_ipc(
        &mut self,
        source: crate::query::export::ExportSource,
        file_path: &std::path::Path,
        options: crate::export::arrow::ArrowExportOptions,
    ) -> Result<u64, crate::export::csv::ExportError> {
        blocking_runtime().block_on(self.export_to_arrow_ipc(source, file_path, options))
    }
}

impl std::fmt::Debug for Connection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Connection")
            .field("session_id", &self.session.session_id())
            .field("host", &self.params.host)
            .field("port", &self.params.port)
            .field("username", &self.params.username)
            .field("in_transaction", &self.session.in_transaction())
            .finish()
    }
}

/// Builder for creating Connection instances.
pub struct ConnectionBuilder {
    /// Connection parameters builder
    params_builder: crate::connection::params::ConnectionBuilder,
}

impl ConnectionBuilder {
    /// Create a new ConnectionBuilder.
    pub fn new() -> Self {
        Self {
            params_builder: crate::connection::params::ConnectionBuilder::new(),
        }
    }

    /// Set the database host.
    pub fn host(mut self, host: &str) -> Self {
        self.params_builder = self.params_builder.host(host);
        self
    }

    /// Set the database port.
    pub fn port(mut self, port: u16) -> Self {
        self.params_builder = self.params_builder.port(port);
        self
    }

    /// Set the username.
    pub fn username(mut self, username: &str) -> Self {
        self.params_builder = self.params_builder.username(username);
        self
    }

    /// Set the password.
    pub fn password(mut self, password: &str) -> Self {
        self.params_builder = self.params_builder.password(password);
        self
    }

    /// Set the default schema.
    pub fn schema(mut self, schema: &str) -> Self {
        self.params_builder = self.params_builder.schema(schema);
        self
    }

    /// Enable or disable TLS.
    pub fn use_tls(mut self, use_tls: bool) -> Self {
        self.params_builder = self.params_builder.use_tls(use_tls);
        self
    }

    /// Enable or disable server-certificate validation.
    ///
    /// Disable when connecting to an Exasol Docker container, which ships a
    /// self-signed certificate that would otherwise fail validation.
    pub fn validate_server_certificate(mut self, validate: bool) -> Self {
        self.params_builder = self.params_builder.validate_server_certificate(validate);
        self
    }

    /// Build and connect.
    ///
    /// # Returns
    ///
    /// A connected `Connection` instance.
    ///
    /// # Errors
    ///
    /// Returns `ExasolError` if the connection fails.
    pub async fn connect(self) -> Result<Connection, ExasolError> {
        let params = self.params_builder.build()?;
        Ok(Connection::from_params(params).await?)
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn secs_ceil_reserves_zero_for_the_unlimited_reset_only() {
        // Zero maps to zero: the "no timeout / reset to unlimited" sentinel.
        assert_eq!(secs_ceil(Duration::from_millis(0)), 0);
        // Any positive sub-second timeout rounds UP to at least one second so
        // it never collapses into the unlimited sentinel.
        assert_eq!(secs_ceil(Duration::from_nanos(1)), 1);
        assert_eq!(secs_ceil(Duration::from_millis(1)), 1);
        assert_eq!(secs_ceil(Duration::from_millis(999)), 1);
        assert_eq!(secs_ceil(Duration::from_millis(1000)), 1);
        // Whole-plus-a-remainder rounds up to the next whole second.
        assert_eq!(secs_ceil(Duration::from_millis(1001)), 2);
        assert_eq!(secs_ceil(Duration::from_millis(2500)), 3);
        // Exact whole seconds are unchanged.
        assert_eq!(secs_ceil(Duration::from_secs(60)), 60);
    }

    #[test]
    fn map_execution_error_recognizes_server_query_timeout() {
        // Primary signal: SQL state R0001 (WebSocket transport phrasing).
        let ws = TransportError::ProtocolError(
            "Query terminated because timeout has been reached. (SQL code: R0001)".to_string(),
        );
        assert!(matches!(
            map_execution_error(ws, 5000),
            QueryError::Timeout { timeout_ms: 5000 }
        ));

        // Primary signal survives the native transport phrasing ("SQL state").
        let native = TransportError::ProtocolError(
            "Query terminated because timeout has been reached. (SQL state: R0001)".to_string(),
        );
        assert!(matches!(
            map_execution_error(native, 1000),
            QueryError::Timeout { timeout_ms: 1000 }
        ));

        // Fallback signal: the message text alone, without the code.
        let text_only = TransportError::ProtocolError(
            "Query terminated because timeout has been reached.".to_string(),
        );
        assert!(matches!(
            map_execution_error(text_only, 2000),
            QueryError::Timeout { timeout_ms: 2000 }
        ));
    }

    #[test]
    fn map_execution_error_passes_through_other_failures() {
        let other = TransportError::ProtocolError(
            "syntax error, unexpected ')' (SQL code: 42000)".to_string(),
        );
        match map_execution_error(other, 5000) {
            QueryError::ExecutionFailed(msg) => assert!(msg.contains("42000")),
            other => panic!("expected ExecutionFailed, got {:?}", other),
        }
    }

    #[test]
    fn map_execution_error_with_zero_effective_timeout_is_not_classified_as_timeout() {
        // An R0001 abort with no driver-configured timeout in effect (e.g. an
        // ambient session-level QUERY_TIMEOUT the driver never set) must not
        // be reported as `QueryError::Timeout { timeout_ms: 0 }` — that would
        // read as "the client timed out immediately", which is false. The
        // server's own message is preserved via ExecutionFailed instead.
        let ambient = TransportError::ProtocolError(
            "Query terminated because timeout has been reached. (SQL code: R0001)".to_string(),
        );
        match map_execution_error(ambient, 0) {
            QueryError::ExecutionFailed(msg) => assert!(msg.contains("R0001")),
            other => panic!("expected ExecutionFailed, got {:?}", other),
        }
    }

    // ========================================================================
    // Mock-transport harness
    //
    // Every test below drives a real `Connection` over the shared
    // `TransportProtocol` mock, so the connection's own logic — parameter
    // mapping, generated SQL, timeout reconciliation, transaction bookkeeping —
    // is asserted without a live Exasol or any network I/O.
    // ========================================================================

    use crate::connection::session::SessionState;
    use crate::transport::messages::SessionInfo as TransportSessionInfo;
    use crate::transport::test_support::{transport_session_info, MockTransport};
    use std::sync::Mutex as SyncMutex;

    /// Every SQL string the mocked transport was asked to execute, in order.
    type SqlLog = Arc<SyncMutex<Vec<String>>>;

    fn new_sql_log() -> SqlLog {
        Arc::new(SyncMutex::new(Vec::new()))
    }

    fn recorded(log: &SqlLog) -> Vec<String> {
        log.lock().expect("SQL log poisoned").clone()
    }

    /// The single SQL statement the connection issued.
    ///
    /// Panics when the count is not exactly one, so a test that means to assert
    /// on "the" statement can never silently assert on the first of several.
    fn only_sql(log: &SqlLog) -> String {
        let statements = recorded(log);
        assert_eq!(
            statements.len(),
            1,
            "expected exactly one statement, got {:?}",
            statements
        );
        statements.into_iter().next().unwrap()
    }

    fn test_params() -> ConnectionParams {
        ConnectionParams::builder()
            .host("db.example.invalid")
            .port(8563)
            .username("tester")
            .password("s3cr3t-pw")
            .build()
            .expect("test connection params must be valid")
    }

    /// A transport that connects and authenticates cleanly and records the SQL
    /// it is handed, answering every statement with a zero-row row count.
    fn recording_transport(log: &SqlLog) -> MockTransport {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        let log = Arc::clone(log);
        transport.expect_execute_query().returning(move |sql| {
            log.lock().expect("SQL log poisoned").push(sql.to_string());
            Ok(QueryResult::row_count(0))
        });
        transport
    }

    /// A connected `Connection` over `recording_transport`, with no default
    /// schema so the only recorded SQL is what the test itself triggers.
    async fn connected(log: &SqlLog) -> Connection {
        Connection::connect_with_transport(test_params(), recording_transport(log))
            .await
            .expect("mock transport must connect")
    }

    /// Scenario: Capability check is in-process and round-trip-free
    #[tokio::test]
    async fn capability_checks_issue_no_sql() {
        let log = new_sql_log();
        let conn = connected(&log).await;

        conn.supports_native_parquet_import();
        for (major, minor, patch) in [(0, 0, 0), (8, 27, 1), (2025, 1, 11), (u32::MAX, 0, 0)] {
            conn.session.supports_at_least(major, minor, patch);
        }

        assert!(
            recorded(&log).is_empty(),
            "capability checks must answer from the login release version"
        );
    }

    // ------------------------------------------------------------------------
    // Metadata SQL builders
    // ------------------------------------------------------------------------

    #[tokio::test]
    async fn get_catalogs_selects_distinct_schema_names_as_catalogs() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        conn.get_catalogs()
            .await
            .expect("get_catalogs must succeed");

        assert_eq!(
            only_sql(&log),
            "SELECT DISTINCT SCHEMA_NAME AS CATALOG_NAME FROM SYS.EXA_ALL_SCHEMAS ORDER BY CATALOG_NAME"
        );
    }

    #[tokio::test]
    async fn get_schemas_without_filter_omits_the_where_clause() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        conn.get_schemas(None).await.expect("get_schemas");

        assert_eq!(
            only_sql(&log),
            "SELECT SCHEMA_NAME FROM SYS.EXA_ALL_SCHEMAS ORDER BY SCHEMA_NAME"
        );
    }

    #[tokio::test]
    async fn get_schemas_with_catalog_filters_on_schema_name() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        conn.get_schemas(Some("SALES")).await.expect("get_schemas");

        assert_eq!(
            only_sql(&log),
            "SELECT SCHEMA_NAME FROM SYS.EXA_ALL_SCHEMAS WHERE SCHEMA_NAME = 'SALES' ORDER BY SCHEMA_NAME"
        );
    }

    #[tokio::test]
    async fn get_schemas_doubles_single_quotes_in_the_filter() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        conn.get_schemas(Some("O'BRIEN"))
            .await
            .expect("get_schemas");

        assert_eq!(
            only_sql(&log),
            "SELECT SCHEMA_NAME FROM SYS.EXA_ALL_SCHEMAS WHERE SCHEMA_NAME = 'O''BRIEN' ORDER BY SCHEMA_NAME"
        );
    }

    #[tokio::test]
    async fn get_tables_without_filters_restricts_to_tables_and_views_only() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        conn.get_tables(None, None, None).await.expect("get_tables");

        assert_eq!(
            only_sql(&log),
            "SELECT ROOT_NAME AS TABLE_SCHEMA, OBJECT_NAME AS TABLE_NAME, OBJECT_TYPE AS TABLE_TYPE \
             FROM SYS.EXA_ALL_OBJECTS WHERE OBJECT_TYPE IN ('TABLE', 'VIEW') ORDER BY ROOT_NAME, OBJECT_NAME"
        );
    }

    #[tokio::test]
    async fn get_tables_ignores_the_catalog_argument_because_exasol_has_no_catalogs() {
        let with_catalog = new_sql_log();
        let mut conn = connected(&with_catalog).await;
        conn.get_tables(Some("ANY_CATALOG"), None, None)
            .await
            .expect("get_tables");

        let without_catalog = new_sql_log();
        let mut conn = connected(&without_catalog).await;
        conn.get_tables(None, None, None).await.expect("get_tables");

        assert_eq!(only_sql(&with_catalog), only_sql(&without_catalog));
    }

    #[tokio::test]
    async fn get_tables_filters_on_schema_and_table_when_both_are_given() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        conn.get_tables(None, Some("SALES"), Some("ORDERS"))
            .await
            .expect("get_tables");

        assert_eq!(
            only_sql(&log),
            "SELECT ROOT_NAME AS TABLE_SCHEMA, OBJECT_NAME AS TABLE_NAME, OBJECT_TYPE AS TABLE_TYPE \
             FROM SYS.EXA_ALL_OBJECTS WHERE OBJECT_TYPE IN ('TABLE', 'VIEW') AND ROOT_NAME = 'SALES' \
             AND OBJECT_NAME = 'ORDERS' ORDER BY ROOT_NAME, OBJECT_NAME"
        );
    }

    #[tokio::test]
    async fn get_tables_doubles_single_quotes_in_schema_and_table_filters() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        conn.get_tables(None, Some("IT'S"), Some("O'HARA"))
            .await
            .expect("get_tables");

        let sql = only_sql(&log);
        assert!(
            sql.contains("ROOT_NAME = 'IT''S'"),
            "schema filter must be escaped, got: {}",
            sql
        );
        assert!(
            sql.contains("OBJECT_NAME = 'O''HARA'"),
            "table filter must be escaped, got: {}",
            sql
        );
    }

    #[tokio::test]
    async fn get_columns_without_filters_omits_the_where_clause() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        conn.get_columns(None, None, None, None)
            .await
            .expect("get_columns");

        let sql = only_sql(&log);
        assert!(
            !sql.contains("WHERE"),
            "unfiltered get_columns must not emit a WHERE clause, got: {}",
            sql
        );
        assert!(sql.contains("FROM SYS.EXA_ALL_COLUMNS"), "got: {}", sql);
        assert!(
            sql.contains("ORDER BY COLUMN_SCHEMA, COLUMN_TABLE, ORDINAL_POSITION"),
            "got: {}",
            sql
        );
    }

    #[tokio::test]
    async fn get_columns_filters_on_schema_table_and_column() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        conn.get_columns(None, Some("SALES"), Some("ORDERS"), Some("ID"))
            .await
            .expect("get_columns");

        let sql = only_sql(&log);
        assert!(
            sql.contains(
                "WHERE COLUMN_SCHEMA = 'SALES' AND COLUMN_TABLE = 'ORDERS' AND COLUMN_NAME = 'ID'"
            ),
            "got: {}",
            sql
        );
    }

    /// Exasol has no catalog level, so `get_columns` treats a catalog argument
    /// as a second schema predicate rather than ignoring it. Passing both a
    /// catalog and a differing schema therefore yields two conflicting
    /// `COLUMN_SCHEMA` predicates and matches nothing — recorded here as the
    /// current contract so a future change to it is a deliberate one.
    #[tokio::test]
    async fn get_columns_maps_the_catalog_argument_onto_column_schema() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        conn.get_columns(Some("CAT"), Some("SALES"), None, None)
            .await
            .expect("get_columns");

        let sql = only_sql(&log);
        assert!(
            sql.contains("WHERE COLUMN_SCHEMA = 'CAT' AND COLUMN_SCHEMA = 'SALES'"),
            "got: {}",
            sql
        );
    }

    #[tokio::test]
    async fn get_columns_doubles_single_quotes_in_every_filter() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        conn.get_columns(Some("C'AT"), Some("S'CH"), Some("T'BL"), Some("C'OL"))
            .await
            .expect("get_columns");

        let sql = only_sql(&log);
        for expected in [
            "COLUMN_SCHEMA = 'C''AT'",
            "COLUMN_SCHEMA = 'S''CH'",
            "COLUMN_TABLE = 'T''BL'",
            "COLUMN_NAME = 'C''OL'",
        ] {
            assert!(
                sql.contains(expected),
                "expected escaped predicate {} in: {}",
                expected,
                sql
            );
        }
    }

    // ------------------------------------------------------------------------
    // Connection setup: connect_with_transport
    // ------------------------------------------------------------------------

    /// A slot a mock expectation writes its observed argument into.
    type Captured<T> = Arc<SyncMutex<Option<T>>>;

    fn new_capture<T>() -> Captured<T> {
        Arc::new(SyncMutex::new(None))
    }

    fn captured<T: Clone>(slot: &Captured<T>) -> T {
        slot.lock()
            .expect("capture poisoned")
            .clone()
            .expect("expectation was never called")
    }

    #[tokio::test]
    async fn connect_maps_every_connection_parameter_onto_the_transport() {
        let observed: Captured<TransportConnectionParams> = new_capture();
        let mut transport = MockTransport::new();
        let sink = Arc::clone(&observed);
        transport.expect_connect().returning(move |params| {
            *sink.lock().expect("capture poisoned") = Some(params.clone());
            Ok(())
        });
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));

        let params = ConnectionParams::builder()
            .host("db.example.invalid")
            .port(9999)
            .username("tester")
            .password("s3cr3t-pw")
            .use_tls(false)
            .validate_server_certificate(false)
            .connection_timeout(Duration::from_millis(4_500))
            .certificate_fingerprint("ab12cd34")
            .build()
            .expect("params");

        Connection::connect_with_transport(params, transport)
            .await
            .expect("connect");

        let mapped = captured(&observed);
        assert_eq!(mapped.host, "db.example.invalid");
        assert_eq!(mapped.port, 9999);
        assert!(!mapped.use_tls);
        assert!(!mapped.validate_server_certificate);
        assert_eq!(mapped.timeout_ms, 4_500);
        assert_eq!(
            mapped.certificate_fingerprint.as_deref(),
            Some("ab12cd34"),
            "a configured fingerprint must be pinned on the transport"
        );
    }

    #[tokio::test]
    async fn connect_leaves_the_fingerprint_unset_when_none_is_configured() {
        let observed: Captured<TransportConnectionParams> = new_capture();
        let mut transport = MockTransport::new();
        let sink = Arc::clone(&observed);
        transport.expect_connect().returning(move |params| {
            *sink.lock().expect("capture poisoned") = Some(params.clone());
            Ok(())
        });
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));

        Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        assert!(captured(&observed).certificate_fingerprint.is_none());
    }

    #[tokio::test]
    async fn connect_forwards_the_configured_username_and_password() {
        let observed: Captured<(String, String)> = new_capture();
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        let sink = Arc::clone(&observed);
        transport
            .expect_authenticate()
            .returning(move |credentials| {
                *sink.lock().expect("capture poisoned") =
                    Some((credentials.username.clone(), credentials.password.clone()));
                Ok(transport_session_info())
            });

        Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        assert_eq!(
            captured(&observed),
            ("tester".to_string(), "s3cr3t-pw".to_string())
        );
    }

    #[tokio::test]
    async fn connect_pushes_a_configured_query_timeout_rounded_up_to_whole_seconds() {
        let observed: Captured<u64> = new_capture();
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        let sink = Arc::clone(&observed);
        transport
            .expect_set_query_timeout()
            .times(1)
            .returning(move |secs| {
                *sink.lock().expect("capture poisoned") = Some(secs);
                Ok(())
            });

        let params = ConnectionParams::builder()
            .host("db.example.invalid")
            .username("tester")
            .password("s3cr3t-pw")
            .query_timeout(Duration::from_millis(1_500))
            .build()
            .expect("params");

        let conn = Connection::connect_with_transport(params, transport)
            .await
            .expect("connect");

        assert_eq!(captured(&observed), 2, "1500ms must round up to 2s");
        assert_eq!(
            conn.session.config().query_timeout,
            Some(Duration::from_millis(1_500)),
            "the session baseline must record the configured value verbatim"
        );
    }

    /// Absent configuration, no `queryTimeout` attribute is set at all so the
    /// server's own `QUERY_TIMEOUT` governs. `MockTransport` has no
    /// `set_query_timeout` expectation here, so any call would panic.
    #[tokio::test]
    async fn connect_sets_no_query_timeout_when_none_is_configured() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));

        let conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        assert_eq!(conn.session.config().query_timeout, None);
    }

    #[tokio::test]
    async fn connect_seeds_the_session_from_the_authentication_response() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));

        let params = ConnectionParams::builder()
            .host("db.example.invalid")
            .username("tester")
            .password("s3cr3t-pw")
            .build()
            .expect("params");

        let conn = Connection::connect_with_transport(params, transport)
            .await
            .expect("connect");

        assert_eq!(conn.session_id(), "1739284756");
        let server = conn.session.server_info();
        assert_eq!(server.release_version, "8.32.0");
        assert_eq!(server.database_name, "exadb");
        assert_eq!(server.product_name, "EXASolution");
        assert_eq!(server.max_data_message_size, 64 * 1024);
        assert_eq!(server.time_zone, "Europe/Berlin");
        assert_eq!(server.max_identifier_length, 128);
        assert_eq!(server.max_varchar_length, 2_000_000);
        assert_eq!(server.identifier_quote_string, "\"");
    }

    #[tokio::test]
    async fn connect_defaults_the_session_time_zone_to_utc_when_the_server_reports_none() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport.expect_authenticate().returning(|_| {
            Ok(TransportSessionInfo {
                time_zone: None,
                ..transport_session_info()
            })
        });

        let conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        assert_eq!(conn.session.server_info().time_zone, "UTC");
    }

    #[tokio::test]
    async fn connect_reports_a_transport_connect_failure_with_host_and_port() {
        let mut transport = MockTransport::new();
        transport
            .expect_connect()
            .returning(|_| Err(TransportError::IoError("refused".to_string())));

        let error = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect_err("a failing transport must fail the connection");

        match error {
            ConnectionError::ConnectionFailed {
                host,
                port,
                message,
            } => {
                assert_eq!(host, "db.example.invalid");
                assert_eq!(port, 8563);
                assert!(message.contains("refused"), "got: {}", message);
            }
            other => panic!("expected ConnectionFailed, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn connect_reports_an_authentication_failure_as_authentication_failed() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Err(TransportError::ProtocolError("bad credentials".to_string())));

        let error = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect_err("failed authentication must fail the connection");

        match error {
            ConnectionError::AuthenticationFailed(message) => {
                assert!(message.contains("bad credentials"), "got: {}", message);
            }
            other => panic!("expected AuthenticationFailed, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn connect_fails_when_the_server_rejects_the_configured_query_timeout() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_set_query_timeout()
            .returning(|_| Err(TransportError::ProtocolError("not permitted".to_string())));

        let params = ConnectionParams::builder()
            .host("db.example.invalid")
            .username("tester")
            .password("s3cr3t-pw")
            .query_timeout(Duration::from_secs(30))
            .build()
            .expect("params");

        let error = Connection::connect_with_transport(params, transport)
            .await
            .expect_err("a rejected query timeout must fail the connection");

        match error {
            ConnectionError::ConnectionFailed { message, .. } => {
                assert!(
                    message.contains("failed to set query timeout"),
                    "got: {}",
                    message
                );
                assert!(message.contains("not permitted"), "got: {}", message);
            }
            other => panic!("expected ConnectionFailed, got {:?}", other),
        }
    }

    // --- the URI schema ---

    fn params_with_schema(schema: &str) -> ConnectionParams {
        ConnectionParams::builder()
            .host("db.example.invalid")
            .port(8563)
            .username("tester")
            .password("s3cr3t-pw")
            .schema(schema)
            .build()
            .expect("params")
    }

    /// Scenario: Schema in connection params is opened on connect
    #[tokio::test]
    async fn connect_sets_the_uri_schema_as_a_session_attribute_after_login() {
        let log = new_sql_log();
        let mut login_order = mockall::Sequence::new();
        let mut transport = MockTransport::new();
        transport
            .expect_connect()
            .times(1)
            .in_sequence(&mut login_order)
            .returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .times(1)
            .in_sequence(&mut login_order)
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_set_query_timeout()
            .times(1)
            .in_sequence(&mut login_order)
            .returning(|_| Ok(()));
        transport
            .expect_set_current_schema()
            .withf(|schema| schema == "sales")
            .times(1)
            .in_sequence(&mut login_order)
            .returning(|_| Ok(()));
        transport
            .expect_current_schema()
            .returning(|| Some("SALES".to_string()));
        let sink = Arc::clone(&log);
        transport.expect_execute_query().returning(move |sql| {
            sink.lock().expect("SQL log poisoned").push(sql.to_string());
            Ok(QueryResult::row_count(0))
        });
        let params = ConnectionParams::builder()
            .host("db.example.invalid")
            .username("tester")
            .password("s3cr3t-pw")
            .schema("sales")
            .query_timeout(Duration::from_secs(30))
            .build()
            .expect("params");

        let conn = Connection::connect_with_transport(params, transport)
            .await
            .expect("connect");

        assert!(
            recorded(&log).is_empty(),
            "connect must not send OPEN SCHEMA"
        );
        assert_eq!(conn.current_schema().await, Some("SALES".to_string()));
    }

    /// Scenario: Schema activation failure surfaces during connect
    #[tokio::test]
    async fn connect_fails_and_closes_the_transport_for_any_rejected_uri_schema() {
        let rejections = [
            "schema ZZ_TYPO not found (SQL state: 42000)",
            "insufficient privileges for schema ZZ_TYPO (SQL state: 42500)",
            "connection reset by peer",
        ];
        for rejection in rejections {
            let mut transport = MockTransport::new();
            transport.expect_connect().returning(|_| Ok(()));
            transport
                .expect_authenticate()
                .returning(|_| Ok(transport_session_info()));
            transport
                .expect_set_current_schema()
                .times(1)
                .returning(move |_| Err(TransportError::ProtocolError(rejection.to_string())));
            transport.expect_close().times(1).returning(|| Ok(()));

            let error =
                Connection::connect_with_transport(params_with_schema("ZZ_TYPO"), transport)
                    .await
                    .expect_err("a rejected URI schema must fail the connection");

            match error {
                ConnectionError::ConnectionFailed {
                    host,
                    port,
                    message,
                } => {
                    assert_eq!(host, "db.example.invalid");
                    assert_eq!(port, 8563);
                    assert!(message.contains("ZZ_TYPO"), "got: {message}");
                    assert!(message.contains(rejection), "got: {message}");
                }
                other => panic!("expected ConnectionFailed, got {:?}", other),
            }
        }
    }

    // ------------------------------------------------------------------------
    // execute_statement: queryTimeout reconciliation
    // ------------------------------------------------------------------------

    /// Every `timeout_secs` the connection pushed to the server, in order.
    type TimeoutLog = Arc<SyncMutex<Vec<u64>>>;

    fn new_timeout_log() -> TimeoutLog {
        Arc::new(SyncMutex::new(Vec::new()))
    }

    fn recorded_timeouts(log: &TimeoutLog) -> Vec<u64> {
        log.lock().expect("timeout log poisoned").clone()
    }

    /// A transport that records both the SQL and every pushed `queryTimeout`,
    /// answering each statement with `answer`.
    fn transport_recording_timeouts(
        sql_log: &SqlLog,
        timeout_log: &TimeoutLog,
        answer: fn() -> Result<QueryResult, TransportError>,
    ) -> MockTransport {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        let timeouts = Arc::clone(timeout_log);
        transport.expect_set_query_timeout().returning(move |secs| {
            timeouts.lock().expect("timeout log poisoned").push(secs);
            Ok(())
        });
        let statements = Arc::clone(sql_log);
        transport.expect_execute_query().returning(move |sql| {
            statements
                .lock()
                .expect("SQL log poisoned")
                .push(sql.to_string());
            answer()
        });
        transport
    }

    fn ok_row_count() -> Result<QueryResult, TransportError> {
        Ok(QueryResult::row_count(1))
    }

    fn params_with_query_timeout(timeout: Duration) -> ConnectionParams {
        ConnectionParams::builder()
            .host("db.example.invalid")
            .port(8563)
            .username("tester")
            .password("s3cr3t-pw")
            .query_timeout(timeout)
            .build()
            .expect("params")
    }

    #[tokio::test]
    async fn execute_statement_pushes_a_statement_timeout_the_session_has_not_applied() {
        let sql_log = new_sql_log();
        let timeouts = new_timeout_log();
        let mut conn = Connection::connect_with_transport(
            test_params(),
            transport_recording_timeouts(&sql_log, &timeouts, ok_row_count),
        )
        .await
        .expect("connect");

        let mut stmt = Statement::new("SELECT 1");
        stmt.set_timeout(2_500);
        conn.execute_statement(&stmt).await.expect("execute");

        assert_eq!(
            recorded_timeouts(&timeouts),
            vec![3],
            "2500ms must be pushed as a 3s server-side limit"
        );
        assert_eq!(
            conn.session.config().query_timeout,
            Some(Duration::from_millis(2_500)),
            "the applied baseline must record the statement's request"
        );
    }

    #[tokio::test]
    async fn execute_statement_skips_the_push_when_the_timeout_already_matches() {
        let sql_log = new_sql_log();
        let timeouts = new_timeout_log();
        let mut conn = Connection::connect_with_transport(
            params_with_query_timeout(Duration::from_secs(30)),
            transport_recording_timeouts(&sql_log, &timeouts, ok_row_count),
        )
        .await
        .expect("connect");

        let stmt = conn.create_statement("SELECT 1");
        conn.execute_statement(&stmt).await.expect("execute");

        assert_eq!(
            recorded_timeouts(&timeouts),
            vec![30],
            "only connect may push; the statement matches the applied value"
        );
    }

    /// A statement carrying no timeout must reset the session-level
    /// `queryTimeout` to `0` (unlimited) so it never inherits a prior
    /// statement's limit.
    #[tokio::test]
    async fn execute_statement_resets_the_server_to_unlimited_for_an_untimed_statement() {
        let sql_log = new_sql_log();
        let timeouts = new_timeout_log();
        let mut conn = Connection::connect_with_transport(
            params_with_query_timeout(Duration::from_secs(10)),
            transport_recording_timeouts(&sql_log, &timeouts, ok_row_count),
        )
        .await
        .expect("connect");

        conn.execute_statement(&Statement::new("SELECT 1"))
            .await
            .expect("execute");

        assert_eq!(recorded_timeouts(&timeouts), vec![10, 0]);
        assert_eq!(conn.session.config().query_timeout, None);
    }

    /// The server's `queryTimeout` was changed before the statement ran, so the
    /// recorded baseline must reflect that even when the statement then aborts —
    /// otherwise the next statement reconciles against a stale value and skips
    /// a push it actually needs.
    #[tokio::test]
    async fn execute_statement_records_the_applied_timeout_even_when_the_query_fails() {
        let sql_log = new_sql_log();
        let timeouts = new_timeout_log();
        let mut conn = Connection::connect_with_transport(
            test_params(),
            transport_recording_timeouts(&sql_log, &timeouts, || {
                Err(TransportError::ProtocolError("boom".to_string()))
            }),
        )
        .await
        .expect("connect");

        let mut stmt = Statement::new("SELECT 1");
        stmt.set_timeout(5_000);
        conn.execute_statement(&stmt)
            .await
            .expect_err("the query must fail");

        assert_eq!(recorded_timeouts(&timeouts), vec![5]);
        assert_eq!(
            conn.session.config().query_timeout,
            Some(Duration::from_millis(5_000))
        );
    }

    #[tokio::test]
    async fn execute_statement_fails_when_the_server_rejects_the_timeout_push() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_set_query_timeout()
            .returning(|_| Err(TransportError::ProtocolError("rejected".to_string())));

        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        let mut stmt = Statement::new("SELECT 1");
        stmt.set_timeout(1_000);
        match conn.execute_statement(&stmt).await {
            Err(QueryError::ExecutionFailed(message)) => {
                assert!(message.contains("rejected"), "got: {}", message)
            }
            other => panic!("expected ExecutionFailed, got {:?}", other),
        }
    }

    /// The reported `timeout_ms` is the limit the server actually enforced —
    /// the request rounded up to whole seconds — not the raw sub-second request.
    #[tokio::test]
    async fn execute_statement_reports_a_server_timeout_abort_with_the_effective_limit() {
        let sql_log = new_sql_log();
        let timeouts = new_timeout_log();
        let mut conn = Connection::connect_with_transport(
            test_params(),
            transport_recording_timeouts(&sql_log, &timeouts, || {
                Err(TransportError::ProtocolError(
                    "Query terminated because timeout has been reached. (SQL code: R0001)"
                        .to_string(),
                ))
            }),
        )
        .await
        .expect("connect");

        let mut stmt = Statement::new("SELECT 1");
        stmt.set_timeout(1_500);
        match conn.execute_statement(&stmt).await {
            Err(QueryError::Timeout { timeout_ms }) => assert_eq!(
                timeout_ms, 2_000,
                "a 1500ms request is enforced as a 2000ms server-side limit"
            ),
            other => panic!("expected Timeout, got {:?}", other),
        }
    }

    /// Scenario: A closed session rejects operations as closed
    #[tokio::test]
    async fn execute_statement_rejects_a_closed_session_as_an_invalid_state() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;
        conn.session.set_state(SessionState::Closed).await;

        match conn.execute_statement(&Statement::new("SELECT 1")).await {
            Err(QueryError::InvalidState(message)) => {
                assert!(message.contains("Connection is closed"), "got: {}", message)
            }
            other => panic!("expected InvalidState, got {:?}", other),
        }
        assert!(
            recorded(&log).is_empty(),
            "no SQL may reach the server from a closed session"
        );
    }

    #[tokio::test]
    async fn execute_statement_propagates_an_unbound_parameter_before_reaching_the_server() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        match conn.execute_statement(&Statement::new("SELECT ?")).await {
            Err(QueryError::ParameterBindingError { index, .. }) => assert_eq!(index, 0),
            other => panic!("expected ParameterBindingError, got {:?}", other),
        }
        assert!(
            recorded(&log).is_empty(),
            "an unbuildable statement must never reach the server"
        );
    }

    #[tokio::test]
    async fn execute_statement_returns_the_session_to_ready_and_counts_the_query() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        conn.execute_statement(&Statement::new("SELECT 1"))
            .await
            .expect("execute");

        assert_eq!(conn.session.state().await, SessionState::Ready);
        assert_eq!(conn.session.query_count(), 1);
    }

    #[tokio::test]
    async fn execute_statement_returns_the_session_to_in_transaction_inside_a_transaction() {
        let sql_log = new_sql_log();
        let mut transport = recording_transport(&sql_log);
        transport.expect_set_autocommit().returning(|_| Ok(()));
        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");
        conn.begin_transaction().await.expect("begin");

        conn.execute_statement(&Statement::new("SELECT 1"))
            .await
            .expect("execute");

        assert_eq!(conn.session.state().await, SessionState::InTransaction);
    }

    #[tokio::test]
    async fn create_statement_inherits_the_connections_configured_query_timeout() {
        let sql_log = new_sql_log();
        let timeouts = new_timeout_log();
        let conn = Connection::connect_with_transport(
            params_with_query_timeout(Duration::from_millis(7_200)),
            transport_recording_timeouts(&sql_log, &timeouts, ok_row_count),
        )
        .await
        .expect("connect");

        assert_eq!(
            conn.create_statement("SELECT 1").timeout_ms(),
            Some(7_200),
            "the raw configured value is carried onto the statement verbatim"
        );
    }

    #[tokio::test]
    async fn create_statement_leaves_the_timeout_unset_when_none_is_configured() {
        let log = new_sql_log();
        let conn = connected(&log).await;

        assert_eq!(conn.create_statement("SELECT 1").timeout_ms(), None);
    }

    #[tokio::test]
    async fn query_fetches_every_batch_of_a_complete_result_set() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_execute_query()
            .returning(|_| Ok(single_decimal_result_set()));

        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        let batches = conn.query("SELECT 1").await.expect("query");

        assert_eq!(batches.len(), 1);
        assert_eq!(batches[0].num_rows(), 1);
        assert_eq!(batches[0].num_columns(), 1);
    }

    #[tokio::test]
    async fn query_rejects_a_statement_that_returns_only_a_row_count() {
        let log = new_sql_log();
        let mut conn = connected(&log).await;

        match conn.query("DELETE FROM T").await {
            Err(QueryError::NoResultSet(_)) => {}
            other => panic!("expected NoResultSet, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn execute_update_returns_the_affected_row_count() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_execute_query()
            .returning(|_| Ok(QueryResult::row_count(5)));

        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        assert_eq!(
            conn.execute_update("DELETE FROM T").await.expect("update"),
            5
        );
    }

    #[tokio::test]
    async fn execute_statement_update_returns_the_affected_row_count() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_execute_query()
            .returning(|_| Ok(QueryResult::row_count(42)));

        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        assert_eq!(
            conn.execute_statement_update(&Statement::new("DELETE FROM T"))
                .await
                .expect("update"),
            42
        );
    }

    #[tokio::test]
    async fn execute_statement_update_rejects_a_statement_that_returns_a_result_set() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_execute_query()
            .returning(|_| Ok(single_decimal_result_set()));

        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        match conn
            .execute_statement_update(&Statement::new("SELECT 1"))
            .await
        {
            Err(QueryError::NoResultSet(_)) => {}
            other => panic!("expected NoResultSet, got {:?}", other),
        }
    }

    /// A one-row, one-column DECIMAL result set — the smallest well-formed
    /// `ResultSet` answer a mocked transport can give.
    fn single_decimal_result_set() -> QueryResult {
        use crate::transport::messages::{ColumnInfo, DataType, ResultData, ResultPayload};
        QueryResult::result_set(
            None,
            ResultData {
                columns: vec![ColumnInfo {
                    name: "N".to_string(),
                    data_type: DataType::decimal(18, 0),
                }],
                data: ResultPayload::Json(vec![vec![serde_json::json!(1)]]),
                total_rows: 1,
            },
        )
    }

    // ------------------------------------------------------------------------
    // Transactions
    // ------------------------------------------------------------------------

    /// A connected connection whose transport also accepts autocommit changes.
    async fn connected_for_transactions(log: &SqlLog) -> Connection {
        let mut transport = recording_transport(log);
        transport.expect_set_autocommit().returning(|_| Ok(()));
        Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect")
    }

    #[tokio::test]
    async fn begin_transaction_disables_autocommit_on_the_server() {
        let observed: Captured<bool> = new_capture();
        let sql_log = new_sql_log();
        let mut transport = recording_transport(&sql_log);
        let sink = Arc::clone(&observed);
        transport
            .expect_set_autocommit()
            .times(1)
            .returning(move |enabled| {
                *sink.lock().expect("capture poisoned") = Some(enabled);
                Ok(())
            });
        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        conn.begin_transaction().await.expect("begin");

        assert!(
            !captured(&observed),
            "beginning a transaction must disable autocommit"
        );
        assert!(conn.in_transaction());
        assert!(
            recorded(&sql_log).is_empty(),
            "autocommit is an attribute, not a statement"
        );
    }

    #[tokio::test]
    async fn begin_transaction_fails_when_the_server_rejects_disabling_autocommit() {
        let sql_log = new_sql_log();
        let mut transport = recording_transport(&sql_log);
        transport
            .expect_set_autocommit()
            .returning(|_| Err(TransportError::ProtocolError("no autocommit".to_string())));
        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        match conn.begin_transaction().await {
            Err(QueryError::TransactionError(message)) => {
                assert!(message.contains("no autocommit"), "got: {}", message)
            }
            other => panic!("expected TransactionError, got {:?}", other),
        }
        assert!(
            !conn.in_transaction(),
            "a rejected autocommit change must not mark a transaction active"
        );
    }

    /// Scenario: Starting a second transaction reports the active transaction
    #[tokio::test]
    async fn begin_transaction_rejects_a_second_overlapping_transaction() {
        let sql_log = new_sql_log();
        let mut transport = recording_transport(&sql_log);
        transport
            .expect_set_autocommit()
            .times(1)
            .returning(|_| Ok(()));
        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");
        conn.begin_transaction().await.expect("first begin");

        match conn.begin_transaction().await {
            Err(QueryError::TransactionError(message)) => {
                assert!(
                    message.contains("Transaction already active"),
                    "got: {}",
                    message
                );
                assert!(!message.contains("closed"), "got: {}", message);
            }
            other => panic!("expected TransactionError, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn commit_issues_a_commit_statement_and_ends_the_transaction() {
        let log = new_sql_log();
        let mut conn = connected_for_transactions(&log).await;
        conn.begin_transaction().await.expect("begin");

        conn.commit().await.expect("commit");

        assert_eq!(recorded(&log), vec!["COMMIT".to_string()]);
        assert!(!conn.in_transaction());
        assert_eq!(conn.session.state().await, SessionState::Ready);
    }

    #[tokio::test]
    async fn commit_outside_a_transaction_is_a_no_op() {
        let log = new_sql_log();
        let mut conn = connected_for_transactions(&log).await;

        conn.commit().await.expect("commit");

        assert!(
            recorded(&log).is_empty(),
            "committing without a transaction must issue no SQL"
        );
    }

    #[tokio::test]
    async fn rollback_issues_a_rollback_statement_and_ends_the_transaction() {
        let log = new_sql_log();
        let mut conn = connected_for_transactions(&log).await;
        conn.begin_transaction().await.expect("begin");

        conn.rollback().await.expect("rollback");

        assert_eq!(recorded(&log), vec!["ROLLBACK".to_string()]);
        assert!(!conn.in_transaction());
        assert_eq!(conn.session.state().await, SessionState::Ready);
    }

    #[tokio::test]
    async fn rollback_outside_a_transaction_is_a_no_op() {
        let log = new_sql_log();
        let mut conn = connected_for_transactions(&log).await;

        conn.rollback().await.expect("rollback");

        assert!(
            recorded(&log).is_empty(),
            "rolling back without a transaction must issue no SQL"
        );
    }

    /// A failed `COMMIT` must leave the transaction active rather than silently
    /// clearing it — the work is still uncommitted on the server.
    #[tokio::test]
    async fn commit_keeps_the_transaction_active_when_the_statement_fails() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport.expect_set_autocommit().returning(|_| Ok(()));
        transport
            .expect_execute_query()
            .returning(|_| Err(TransportError::ProtocolError("commit failed".to_string())));

        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");
        conn.begin_transaction().await.expect("begin");

        conn.commit().await.expect_err("commit must fail");

        assert!(conn.in_transaction());
    }

    #[tokio::test]
    async fn in_transaction_is_false_on_a_freshly_connected_connection() {
        let log = new_sql_log();
        let conn = connected(&log).await;

        assert!(!conn.in_transaction());
    }

    /// Scenario: Set the current schema at runtime
    #[tokio::test]
    async fn set_schema_sends_the_schema_attribute_and_reports_the_servers_name() {
        let log = new_sql_log();
        let mut transport = recording_transport(&log);
        transport
            .expect_set_current_schema()
            .withf(|schema| schema == "my_schema")
            .times(1)
            .returning(|_| Ok(()));
        transport
            .expect_current_schema()
            .returning(|| Some("MY_SCHEMA".to_string()));
        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        conn.set_schema("my_schema").await.expect("set_schema");

        assert!(
            recorded(&log).is_empty(),
            "set_schema must not send OPEN SCHEMA"
        );
        assert_eq!(conn.current_schema().await, Some("MY_SCHEMA".to_string()));
    }

    /// Scenario: Set the current schema at runtime
    #[tokio::test]
    async fn set_schema_returns_the_transports_error() {
        let log = new_sql_log();
        let mut transport = recording_transport(&log);
        transport.expect_set_current_schema().returning(|_| {
            Err(TransportError::ProtocolError(
                "schema ZZ_TYPO not found (SQL state: 42000)".to_string(),
            ))
        });
        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        let error = conn
            .set_schema("ZZ_TYPO")
            .await
            .expect_err("a rejected schema must fail set_schema");

        assert!(
            error.to_string().contains("schema ZZ_TYPO not found"),
            "got: {error}"
        );
    }

    #[tokio::test]
    async fn set_schema_rejects_a_closed_session_without_a_request() {
        let log = new_sql_log();
        let mut transport = recording_transport(&log);
        transport.expect_set_current_schema().never();
        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");
        conn.session.set_state(SessionState::Closed).await;

        match conn.set_schema("SALES").await {
            Err(QueryError::InvalidState(_)) => {}
            other => panic!("expected InvalidState, got {:?}", other),
        }
    }

    /// Scenario: Current schema follows schema changes made in SQL
    #[tokio::test]
    async fn current_schema_reports_the_transports_value_without_a_request() {
        let log = new_sql_log();
        let mut transport = recording_transport(&log);
        transport
            .expect_current_schema()
            .returning(|| Some("OPENED_IN_SQL".to_string()));
        transport.expect_refresh_current_schema().never();
        let conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        assert_eq!(
            conn.current_schema().await,
            Some("OPENED_IN_SQL".to_string())
        );
        assert!(recorded(&log).is_empty());
    }

    #[tokio::test]
    async fn refresh_current_schema_returns_the_servers_answer() {
        let log = new_sql_log();
        let mut transport = recording_transport(&log);
        transport
            .expect_refresh_current_schema()
            .times(1)
            .returning(|| Ok(Some("SYS".to_string())));
        let conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        assert_eq!(
            conn.refresh_current_schema().await.expect("refresh"),
            Some("SYS".to_string())
        );
    }

    #[tokio::test]
    async fn refresh_current_schema_surfaces_a_transport_failure() {
        let log = new_sql_log();
        let mut transport = recording_transport(&log);
        transport
            .expect_refresh_current_schema()
            .returning(|| Err(TransportError::ProtocolError("socket closed".to_string())));
        let conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        let error = conn
            .refresh_current_schema()
            .await
            .expect_err("a failed request must surface");

        assert!(error.to_string().contains("socket closed"), "got: {error}");
    }

    // ------------------------------------------------------------------------
    // make_sql_executor
    // ------------------------------------------------------------------------

    #[tokio::test]
    async fn sql_executor_returns_the_row_count_for_a_row_count_result() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_execute_query()
            .returning(|_| Ok(QueryResult::row_count(7)));

        let conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        let execute = conn.make_sql_executor();
        assert_eq!(execute("IMPORT INTO T ...".to_string()).await, Ok(7));
    }

    /// The executor exists for import/export statements, which report a row
    /// count. A statement that unexpectedly answers with a result set reports
    /// zero rows rather than failing the import.
    #[tokio::test]
    async fn sql_executor_reports_zero_rows_for_a_result_set_result() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_execute_query()
            .returning(|_| Ok(single_decimal_result_set()));

        let conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        let execute = conn.make_sql_executor();
        assert_eq!(execute("SELECT 1".to_string()).await, Ok(0));
    }

    #[tokio::test]
    async fn sql_executor_surfaces_a_transport_failure_as_its_message() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_execute_query()
            .returning(|_| Err(TransportError::IoError("socket closed".to_string())));

        let conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        let execute = conn.make_sql_executor();
        let error = execute("IMPORT INTO T ...".to_string())
            .await
            .expect_err("a transport failure must surface");
        assert!(error.contains("socket closed"), "got: {}", error);
    }

    /// Parallel file imports call the executor repeatedly, so it must survive
    /// more than one invocation.
    #[tokio::test]
    async fn sql_executor_is_reusable_across_several_statements() {
        let log = new_sql_log();
        let conn = connected(&log).await;

        let execute = conn.make_sql_executor();
        execute("IMPORT INTO T FROM 'part-0'".to_string())
            .await
            .expect("first");
        execute("IMPORT INTO T FROM 'part-1'".to_string())
            .await
            .expect("second");

        assert_eq!(
            recorded(&log),
            vec![
                "IMPORT INTO T FROM 'part-0'".to_string(),
                "IMPORT INTO T FROM 'part-1'".to_string()
            ]
        );
    }

    // ------------------------------------------------------------------------
    // Debug rendering and the connection builder
    // ------------------------------------------------------------------------

    #[tokio::test]
    async fn debug_output_identifies_the_connection_without_leaking_the_password() {
        let log = new_sql_log();
        let conn = connected(&log).await;

        let rendered = format!("{:?}", conn);

        assert!(
            !rendered.contains("s3cr3t-pw"),
            "the password must never appear in debug output, got: {}",
            rendered
        );
        assert!(!rendered.contains("password"), "got: {}", rendered);
        assert!(rendered.contains("1739284756"), "got: {}", rendered);
        assert!(rendered.contains("db.example.invalid"), "got: {}", rendered);
        assert!(rendered.contains("8563"), "got: {}", rendered);
        assert!(rendered.contains("tester"), "got: {}", rendered);
        assert!(
            rendered.contains("in_transaction: false"),
            "got: {}",
            rendered
        );
    }

    #[tokio::test]
    async fn debug_output_reports_an_active_transaction() {
        let log = new_sql_log();
        let mut conn = connected_for_transactions(&log).await;
        conn.begin_transaction().await.expect("begin");

        assert!(
            format!("{:?}", conn).contains("in_transaction: true"),
            "an active transaction must be visible in debug output"
        );
    }

    #[test]
    fn connection_builder_carries_every_setting_into_the_built_parameters() {
        let builder = ConnectionBuilder::default()
            .host("db.example.invalid")
            .port(9999)
            .username("tester")
            .password("s3cr3t-pw")
            .schema("SALES")
            .use_tls(false)
            .validate_server_certificate(false);

        let params = builder
            .params_builder
            .build()
            .expect("a fully specified builder must produce valid parameters");

        assert_eq!(params.host, "db.example.invalid");
        assert_eq!(params.port, 9999);
        assert_eq!(params.username, "tester");
        assert_eq!(params.password(), "s3cr3t-pw");
        assert_eq!(params.schema.as_deref(), Some("SALES"));
        assert!(!params.use_tls);
        assert!(!params.validate_server_certificate);
    }

    #[test]
    fn connection_builder_validates_the_server_certificate_by_default() {
        let params = ConnectionBuilder::new()
            .host("db.example.invalid")
            .username("tester")
            .password("s3cr3t-pw")
            .params_builder
            .build()
            .expect("params");

        assert!(
            params.validate_server_certificate,
            "certificate validation must stay on unless explicitly disabled"
        );
        assert!(
            params.use_tls,
            "TLS must stay on unless explicitly disabled"
        );
    }

    /// Parameter validation happens before any dialling, so an incomplete
    /// builder fails locally rather than on the network.
    #[tokio::test]
    async fn connection_builder_connect_rejects_a_missing_host_before_dialling() {
        let error = ConnectionBuilder::new()
            .username("tester")
            .password("s3cr3t-pw")
            .connect()
            .await
            .expect_err("a builder without a host must not connect");

        match error {
            ExasolError::Connection(ConnectionError::InvalidParameter { parameter, .. }) => {
                assert_eq!(parameter, "host")
            }
            other => panic!("expected a missing-host InvalidParameter, got {:?}", other),
        }
    }

    /// The connection-string parser already rejects an unknown `transport`, so
    /// this arm is a defence-in-depth guard reachable only by setting the
    /// public field directly. It must still name the transport it refused.
    #[tokio::test]
    async fn from_params_rejects_a_transport_the_build_does_not_provide() {
        let mut params = test_params();
        params.transport = Some("telepathy".to_string());

        let error = Connection::from_params(params)
            .await
            .expect_err("an unavailable transport must not connect");

        match error {
            ConnectionError::InvalidParameter { parameter, message } => {
                assert_eq!(parameter, "transport");
                assert!(
                    message.contains("Transport 'telepathy' is not available"),
                    "got: {}",
                    message
                );
            }
            other => panic!("expected InvalidParameter, got {:?}", other),
        }
    }

    #[test]
    fn connection_builder_entry_point_produces_a_usable_builder() {
        let params = Connection::builder()
            .host("db.example.invalid")
            .username("tester")
            .password("s3cr3t-pw")
            .params_builder
            .build()
            .expect("params");

        assert_eq!(params.host, "db.example.invalid");
    }

    // ------------------------------------------------------------------------
    // Connection lifecycle and accessors
    // ------------------------------------------------------------------------

    #[tokio::test]
    async fn params_exposes_the_parameters_the_connection_was_built_from() {
        let log = new_sql_log();
        let conn = connected(&log).await;

        assert_eq!(conn.params().host, "db.example.invalid");
        assert_eq!(conn.params().port, 8563);
        assert_eq!(conn.params().username, "tester");
    }

    #[tokio::test]
    async fn close_closes_the_session_and_the_transport() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport.expect_close().times(1).returning(|| Ok(()));

        let conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        conn.close().await.expect("close");
    }

    #[tokio::test]
    async fn close_reports_a_failing_transport_with_host_and_port() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_close()
            .returning(|| Err(TransportError::IoError("already gone".to_string())));

        let conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        match conn.close().await {
            Err(ConnectionError::ConnectionFailed {
                host,
                port,
                message,
            }) => {
                assert_eq!(host, "db.example.invalid");
                assert_eq!(port, 8563);
                assert!(message.contains("already gone"), "got: {}", message);
            }
            other => panic!("expected ConnectionFailed, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn is_closed_reflects_the_session_state() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport.expect_close().returning(|| Ok(()));
        transport.expect_is_connected().returning(|| true);

        let conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        assert!(!conn.is_closed().await);
        conn.shutdown().await.expect("shutdown");
        assert!(conn.is_closed().await);
    }

    /// `is_closed()` must report a terminated transport as closed even while
    /// the session itself still believes it is open, so callers see one
    /// consistent answer instead of a stale "open" from session state alone.
    #[tokio::test]
    async fn is_closed_reports_true_when_the_transport_is_terminated() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport.expect_is_connected().returning(|| false);

        let conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        assert!(conn.is_closed().await);
    }

    #[tokio::test]
    async fn shutdown_reports_a_failing_transport_with_host_and_port() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_close()
            .returning(|| Err(TransportError::IoError("already gone".to_string())));

        let conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        match conn.shutdown().await {
            Err(ConnectionError::ConnectionFailed { message, .. }) => {
                assert!(message.contains("already gone"), "got: {}", message)
            }
            other => panic!("expected ConnectionFailed, got {:?}", other),
        }
    }

    // ------------------------------------------------------------------------
    // Prepared statements
    // ------------------------------------------------------------------------

    use crate::transport::protocol::PreparedStatementHandle;

    fn handle_with(num_params: i32) -> PreparedStatementHandle {
        PreparedStatementHandle::new(17, num_params, Vec::new(), Vec::new())
    }

    /// The parameter rows the mocked transport was handed for execution.
    type ParameterLog = Arc<SyncMutex<Vec<Option<Vec<Vec<serde_json::Value>>>>>>;

    /// A connected connection whose transport prepares a `num_params`-parameter
    /// statement, answers every execution with `answer`, and records the
    /// parameters it was given.
    async fn connected_for_prepared(
        num_params: i32,
        answer: fn() -> Result<QueryResult, TransportError>,
        parameters: &ParameterLog,
    ) -> Connection {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_create_prepared_statement()
            .returning(move |_| Ok(handle_with(num_params)));
        let sink = Arc::clone(parameters);
        transport
            .expect_execute_prepared_statement()
            .returning(move |_, params| {
                sink.lock().expect("parameter log poisoned").push(params);
                answer()
            });
        transport
            .expect_close_prepared_statement()
            .returning(|_| Ok(()));
        Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect")
    }

    fn new_parameter_log() -> ParameterLog {
        Arc::new(SyncMutex::new(Vec::new()))
    }

    fn recorded_parameters(log: &ParameterLog) -> Vec<Option<Vec<Vec<serde_json::Value>>>> {
        log.lock().expect("parameter log poisoned").clone()
    }

    fn closed_prepared_statement() -> PreparedStatement {
        let mut stmt = PreparedStatement::new(handle_with(0));
        stmt.mark_closed();
        stmt
    }

    #[tokio::test]
    async fn prepare_returns_a_statement_sized_by_the_servers_parameter_count() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(2, ok_row_count, &parameters).await;

        let stmt = conn
            .prepare("INSERT INTO T VALUES (?, ?)")
            .await
            .expect("prepare");

        assert_eq!(stmt.parameter_count(), 2);
        assert_eq!(stmt.handle(), 17);
        assert!(!stmt.is_closed());
    }

    #[tokio::test]
    async fn prepare_rejects_a_closed_session() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(0, ok_row_count, &parameters).await;
        conn.session.set_state(SessionState::Closed).await;

        match conn.prepare("SELECT 1").await {
            Err(QueryError::InvalidState(_)) => {}
            other => panic!("expected InvalidState, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn prepare_surfaces_a_transport_failure() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_create_prepared_statement()
            .returning(|_| Err(TransportError::ProtocolError("syntax error".to_string())));

        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        match conn.prepare("SELCT 1").await {
            Err(QueryError::ExecutionFailed(message)) => {
                assert!(message.contains("syntax error"), "got: {}", message)
            }
            other => panic!("expected ExecutionFailed, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn execute_prepared_forwards_bound_parameters_in_column_major_order() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(2, ok_row_count, &parameters).await;
        let mut stmt = conn
            .prepare("INSERT INTO T VALUES (?, ?)")
            .await
            .expect("prepare");
        stmt.bind(0, Parameter::Integer(7)).expect("bind 0");
        stmt.bind(1, Parameter::String("seven".to_string()))
            .expect("bind 1");

        conn.execute_prepared(&stmt).await.expect("execute");

        assert_eq!(
            recorded_parameters(&parameters),
            vec![Some(vec![
                vec![serde_json::json!(7)],
                vec![serde_json::json!("seven")]
            ])]
        );
    }

    #[tokio::test]
    async fn execute_prepared_sends_no_parameters_for_a_parameterless_statement() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(0, ok_row_count, &parameters).await;
        let stmt = conn.prepare("DELETE FROM T").await.expect("prepare");

        conn.execute_prepared(&stmt).await.expect("execute");

        assert_eq!(recorded_parameters(&parameters), vec![None]);
    }

    #[tokio::test]
    async fn execute_prepared_rejects_a_closed_statement() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(0, ok_row_count, &parameters).await;

        match conn.execute_prepared(&closed_prepared_statement()).await {
            Err(QueryError::StatementClosed) => {}
            other => panic!("expected StatementClosed, got {:?}", other),
        }
        assert!(
            recorded_parameters(&parameters).is_empty(),
            "a closed statement must never reach the server"
        );
    }

    #[tokio::test]
    async fn execute_prepared_rejects_a_closed_session() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(0, ok_row_count, &parameters).await;
        let stmt = conn.prepare("SELECT 1").await.expect("prepare");
        conn.session.set_state(SessionState::Closed).await;

        match conn.execute_prepared(&stmt).await {
            Err(QueryError::InvalidState(_)) => {}
            other => panic!("expected InvalidState, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn execute_prepared_propagates_an_unbound_parameter() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(1, ok_row_count, &parameters).await;
        let stmt = conn.prepare("SELECT ?").await.expect("prepare");

        match conn.execute_prepared(&stmt).await {
            Err(QueryError::ParameterBindingError { index, .. }) => assert_eq!(index, 0),
            other => panic!("expected ParameterBindingError, got {:?}", other),
        }
        assert!(recorded_parameters(&parameters).is_empty());
    }

    #[tokio::test]
    async fn execute_prepared_surfaces_a_transport_failure() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(
            0,
            || Err(TransportError::ProtocolError("table missing".to_string())),
            &parameters,
        )
        .await;
        let stmt = conn.prepare("SELECT 1").await.expect("prepare");

        match conn.execute_prepared(&stmt).await {
            Err(QueryError::ExecutionFailed(message)) => {
                assert!(message.contains("table missing"), "got: {}", message)
            }
            other => panic!("expected ExecutionFailed, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn execute_prepared_counts_the_query_and_returns_the_session_to_ready() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(0, ok_row_count, &parameters).await;
        let stmt = conn.prepare("SELECT 1").await.expect("prepare");

        conn.execute_prepared(&stmt).await.expect("execute");

        assert_eq!(conn.session.query_count(), 1);
        assert_eq!(conn.session.state().await, SessionState::Ready);
    }

    #[tokio::test]
    async fn execute_prepared_update_returns_the_affected_row_count() {
        let parameters = new_parameter_log();
        let mut conn =
            connected_for_prepared(0, || Ok(QueryResult::row_count(13)), &parameters).await;
        let stmt = conn.prepare("DELETE FROM T").await.expect("prepare");

        assert_eq!(
            conn.execute_prepared_update(&stmt).await.expect("update"),
            13
        );
    }

    #[tokio::test]
    async fn execute_prepared_update_rejects_a_statement_that_returns_a_result_set() {
        let parameters = new_parameter_log();
        let mut conn =
            connected_for_prepared(0, || Ok(single_decimal_result_set()), &parameters).await;
        let stmt = conn.prepare("SELECT 1").await.expect("prepare");

        match conn.execute_prepared_update(&stmt).await {
            Err(QueryError::UnexpectedResultSet) => {}
            other => panic!("expected UnexpectedResultSet, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn execute_prepared_update_rejects_a_closed_statement() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(0, ok_row_count, &parameters).await;

        match conn
            .execute_prepared_update(&closed_prepared_statement())
            .await
        {
            Err(QueryError::StatementClosed) => {}
            other => panic!("expected StatementClosed, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn execute_prepared_update_rejects_a_closed_session() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(0, ok_row_count, &parameters).await;
        let stmt = conn.prepare("DELETE FROM T").await.expect("prepare");
        conn.session.set_state(SessionState::Closed).await;

        match conn.execute_prepared_update(&stmt).await {
            Err(QueryError::InvalidState(_)) => {}
            other => panic!("expected InvalidState, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn execute_batch_update_transposes_parameter_rows_into_columns() {
        let parameters = new_parameter_log();
        let mut conn =
            connected_for_prepared(2, || Ok(QueryResult::row_count(3)), &parameters).await;
        let stmt = conn
            .prepare("INSERT INTO T VALUES (?, ?)")
            .await
            .expect("prepare");

        let affected = conn
            .execute_batch_update(
                &stmt,
                &[
                    vec![Parameter::Integer(1), Parameter::String("a".to_string())],
                    vec![Parameter::Integer(2), Parameter::String("b".to_string())],
                    vec![Parameter::Integer(3), Parameter::String("c".to_string())],
                ],
            )
            .await
            .expect("batch update");

        assert_eq!(affected, 3);
        assert_eq!(
            recorded_parameters(&parameters),
            vec![Some(vec![
                vec![
                    serde_json::json!(1),
                    serde_json::json!(2),
                    serde_json::json!(3)
                ],
                vec![
                    serde_json::json!("a"),
                    serde_json::json!("b"),
                    serde_json::json!("c")
                ]
            ])],
            "row-major input must reach the wire column-major"
        );
    }

    #[tokio::test]
    async fn execute_batch_update_rejects_a_row_whose_length_differs_from_the_statement() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(2, ok_row_count, &parameters).await;
        let stmt = conn
            .prepare("INSERT INTO T VALUES (?, ?)")
            .await
            .expect("prepare");

        match conn
            .execute_batch_update(
                &stmt,
                &[
                    vec![Parameter::Integer(1), Parameter::Integer(2)],
                    vec![Parameter::Integer(3)],
                ],
            )
            .await
        {
            Err(QueryError::ParameterBindingError { index, .. }) => assert_eq!(index, 1),
            other => panic!("expected ParameterBindingError, got {:?}", other),
        }
        assert!(recorded_parameters(&parameters).is_empty());
    }

    #[tokio::test]
    async fn execute_batch_update_rejects_a_statement_that_returns_a_result_set() {
        let parameters = new_parameter_log();
        let mut conn =
            connected_for_prepared(1, || Ok(single_decimal_result_set()), &parameters).await;
        let stmt = conn.prepare("SELECT ?").await.expect("prepare");

        match conn
            .execute_batch_update(&stmt, &[vec![Parameter::Integer(1)]])
            .await
        {
            Err(QueryError::UnexpectedResultSet) => {}
            other => panic!("expected UnexpectedResultSet, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn execute_batch_update_rejects_a_closed_statement() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(0, ok_row_count, &parameters).await;

        match conn
            .execute_batch_update(&closed_prepared_statement(), &[])
            .await
        {
            Err(QueryError::StatementClosed) => {}
            other => panic!("expected StatementClosed, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn execute_batch_update_rejects_a_closed_session() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(1, ok_row_count, &parameters).await;
        let stmt = conn
            .prepare("DELETE FROM T WHERE ID = ?")
            .await
            .expect("prepare");
        conn.session.set_state(SessionState::Closed).await;

        match conn
            .execute_batch_update(&stmt, &[vec![Parameter::Integer(1)]])
            .await
        {
            Err(QueryError::InvalidState(_)) => {}
            other => panic!("expected InvalidState, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn execute_batch_returns_a_result_set_and_counts_the_query() {
        let parameters = new_parameter_log();
        let mut conn =
            connected_for_prepared(1, || Ok(single_decimal_result_set()), &parameters).await;
        let stmt = conn.prepare("SELECT ?").await.expect("prepare");

        let result = conn
            .execute_batch(&stmt, &[vec![Parameter::Integer(1)]])
            .await
            .expect("batch");

        assert!(
            result.row_count().is_none(),
            "a result set has no row count"
        );
        assert_eq!(conn.session.query_count(), 1);
    }

    /// An empty batch mirrors the zero-parameter case: no parameters are sent.
    #[tokio::test]
    async fn execute_batch_with_no_rows_sends_no_parameters() {
        let parameters = new_parameter_log();
        let mut conn =
            connected_for_prepared(1, || Ok(single_decimal_result_set()), &parameters).await;
        let stmt = conn.prepare("SELECT ?").await.expect("prepare");

        conn.execute_batch(&stmt, &[]).await.expect("batch");

        assert_eq!(recorded_parameters(&parameters), vec![None]);
    }

    #[tokio::test]
    async fn execute_batch_rejects_a_closed_statement() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(0, ok_row_count, &parameters).await;

        match conn.execute_batch(&closed_prepared_statement(), &[]).await {
            Err(QueryError::StatementClosed) => {}
            other => panic!("expected StatementClosed, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn execute_batch_rejects_a_closed_session() {
        let parameters = new_parameter_log();
        let mut conn = connected_for_prepared(1, ok_row_count, &parameters).await;
        let stmt = conn.prepare("SELECT ?").await.expect("prepare");
        conn.session.set_state(SessionState::Closed).await;

        match conn
            .execute_batch(&stmt, &[vec![Parameter::Integer(1)]])
            .await
        {
            Err(QueryError::InvalidState(_)) => {}
            other => panic!("expected InvalidState, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn close_prepared_releases_the_server_handle_and_marks_the_statement_closed() {
        let closed: Captured<i32> = new_capture();
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_create_prepared_statement()
            .returning(|_| Ok(handle_with(0)));
        let sink = Arc::clone(&closed);
        transport
            .expect_close_prepared_statement()
            .times(1)
            .returning(move |handle| {
                *sink.lock().expect("capture poisoned") = Some(handle.handle);
                Ok(())
            });

        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");
        let stmt = conn.prepare("SELECT 1").await.expect("prepare");

        conn.close_prepared(stmt).await.expect("close_prepared");

        assert_eq!(captured(&closed), 17);
    }

    /// Closing an already-closed statement must not send a second release for a
    /// handle the server has already freed.
    #[tokio::test]
    async fn close_prepared_on_an_already_closed_statement_sends_nothing() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_close_prepared_statement()
            .times(0)
            .returning(|_| Ok(()));

        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");

        conn.close_prepared(closed_prepared_statement())
            .await
            .expect("closing a closed statement must succeed");
    }

    #[tokio::test]
    async fn close_prepared_surfaces_a_transport_failure() {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport
            .expect_create_prepared_statement()
            .returning(|_| Ok(handle_with(0)));
        transport
            .expect_close_prepared_statement()
            .returning(|_| Err(TransportError::IoError("socket closed".to_string())));

        let mut conn = Connection::connect_with_transport(test_params(), transport)
            .await
            .expect("connect");
        let stmt = conn.prepare("SELECT 1").await.expect("prepare");

        match conn.close_prepared(stmt).await {
            Err(QueryError::ExecutionFailed(message)) => {
                assert!(message.contains("socket closed"), "got: {}", message)
            }
            other => panic!("expected ExecutionFailed, got {:?}", other),
        }
    }

    /// A transport on which every query except `COMMIT` and `ROLLBACK`, every
    /// prepared execution, and every `queryTimeout` push fails, so a test can
    /// fail a statement and still end its transaction.
    fn failing_statement_transport() -> MockTransport {
        let mut transport = MockTransport::new();
        transport.expect_connect().returning(|_| Ok(()));
        transport
            .expect_authenticate()
            .returning(|_| Ok(transport_session_info()));
        transport.expect_execute_query().returning(|sql| {
            if sql == "COMMIT" || sql == "ROLLBACK" {
                Ok(QueryResult::row_count(0))
            } else {
                Err(TransportError::ProtocolError(
                    "object ZZ_NO_SUCH_TABLE not found".to_string(),
                ))
            }
        });
        transport.expect_set_query_timeout().returning(|_| {
            Err(TransportError::ProtocolError(
                "queryTimeout rejected".to_string(),
            ))
        });
        transport
            .expect_create_prepared_statement()
            .returning(|_| Ok(handle_with(0)));
        transport
            .expect_execute_prepared_statement()
            .returning(|_, _| {
                Err(TransportError::ProtocolError(
                    "object ZZ_NO_SUCH_TABLE not found".to_string(),
                ))
            });
        transport.expect_set_autocommit().returning(|_| Ok(()));
        transport
    }

    async fn connected_with_failing_statements() -> Connection {
        Connection::connect_with_transport(test_params(), failing_statement_transport())
            .await
            .expect("connect")
    }

    /// Scenario: A failed statement leaves the session usable
    #[tokio::test]
    async fn failed_execute_statement_leaves_the_session_ready() {
        let mut conn = connected_with_failing_statements().await;

        let server_error = conn.execute_statement(&Statement::new("SELECT 1")).await;
        assert!(server_error.is_err(), "the server rejects the statement");
        assert_eq!(conn.session.state().await, SessionState::Ready);

        let unbound = conn.execute_statement(&Statement::new("SELECT ?")).await;
        assert!(matches!(
            unbound,
            Err(QueryError::ParameterBindingError { .. })
        ));
        assert_eq!(conn.session.state().await, SessionState::Ready);

        let mut timed = Statement::new("SELECT 1");
        timed.set_timeout(5_000);
        let rejected_timeout = conn.execute_statement(&timed).await;
        assert!(
            rejected_timeout.is_err(),
            "the server rejects the queryTimeout push"
        );
        assert_eq!(conn.session.state().await, SessionState::Ready);
    }

    /// Scenario: A failed statement leaves the session usable
    #[tokio::test]
    async fn failed_prepared_executions_leave_the_session_ready() {
        let mut conn = connected_with_failing_statements().await;
        let stmt = conn.prepare("SELECT 1").await.expect("prepare");

        assert!(conn.execute_prepared(&stmt).await.is_err());
        assert_eq!(conn.session.state().await, SessionState::Ready);

        assert!(conn.execute_prepared_update(&stmt).await.is_err());
        assert_eq!(conn.session.state().await, SessionState::Ready);

        assert!(conn.execute_batch_update(&stmt, &[]).await.is_err());
        assert_eq!(conn.session.state().await, SessionState::Ready);

        assert!(conn.execute_batch(&stmt, &[]).await.is_err());
        assert_eq!(conn.session.state().await, SessionState::Ready);
    }

    /// Scenario: A failed statement leaves the session usable
    #[tokio::test]
    async fn begin_transaction_succeeds_after_a_failed_statement() {
        let mut conn = connected_with_failing_statements().await;
        assert!(conn
            .execute_statement(&Statement::new("SELECT 1"))
            .await
            .is_err());

        conn.begin_transaction()
            .await
            .expect("a failed statement must not block the transaction start");

        assert!(conn.in_transaction());
        assert_eq!(conn.session.state().await, SessionState::InTransaction);
    }

    /// Scenario: A failed statement inside a transaction keeps the transaction
    #[tokio::test]
    async fn failed_statement_inside_a_transaction_keeps_the_transaction() {
        let mut conn = connected_with_failing_statements().await;
        let stmt = conn.prepare("SELECT 1").await.expect("prepare");
        conn.begin_transaction().await.expect("begin");

        assert!(conn
            .execute_statement(&Statement::new("SELECT 1"))
            .await
            .is_err());
        assert_eq!(conn.session.state().await, SessionState::InTransaction);

        assert!(conn.execute_prepared(&stmt).await.is_err());
        assert_eq!(conn.session.state().await, SessionState::InTransaction);

        conn.commit().await.expect("commit");
        assert_eq!(conn.session.state().await, SessionState::Ready);

        conn.begin_transaction().await.expect("second begin");
        assert!(conn
            .execute_statement(&Statement::new("SELECT 1"))
            .await
            .is_err());
        conn.rollback().await.expect("rollback");
        assert_eq!(conn.session.state().await, SessionState::Ready);
    }

    /// Scenario: An abandoned execution leaves the session state unchanged
    #[tokio::test(start_paused = true)]
    async fn abandoned_execution_leaves_the_session_state_unchanged() {
        use crate::transport::test_support::GatedQueryTransport;

        for in_transaction in [false, true] {
            let mut mock = MockTransport::new();
            mock.expect_connect().returning(|_| Ok(()));
            mock.expect_authenticate()
                .returning(|_| Ok(transport_session_info()));
            mock.expect_set_autocommit().returning(|_| Ok(()));
            let mut conn = Connection::connect_with_transport(
                test_params(),
                GatedQueryTransport::stalled(mock),
            )
            .await
            .expect("connect");
            if in_transaction {
                conn.begin_transaction().await.expect("begin");
            }
            let before = conn.session.state().await;

            let outcome = tokio::time::timeout(
                Duration::from_millis(50),
                conn.execute_statement(&Statement::new("SELECT 1")),
            )
            .await;

            assert!(outcome.is_err(), "the stalled execution never completes");
            assert_eq!(conn.session.state().await, before);
        }
    }

    /// Scenario: A closed session rejects operations as closed
    #[tokio::test]
    async fn closed_session_rejects_operations_as_closed() {
        for state in [SessionState::Closing, SessionState::Closed] {
            let mut transport = MockTransport::new();
            transport.expect_connect().returning(|_| Ok(()));
            transport
                .expect_authenticate()
                .returning(|_| Ok(transport_session_info()));
            let mut conn = Connection::connect_with_transport(test_params(), transport)
                .await
                .expect("connect");
            let prepared = PreparedStatement::new(handle_with(0));
            conn.session.set_state(state).await;

            let rejections = [
                conn.execute_statement(&Statement::new("SELECT 1"))
                    .await
                    .err(),
                conn.prepare("SELECT 1").await.err(),
                conn.execute_prepared(&prepared).await.err(),
                conn.begin_transaction().await.err(),
            ];

            // The transport mock has no expectation for any request, so a
            // request sent for these operations would have panicked.
            for rejection in rejections {
                let error = rejection.unwrap_or_else(|| panic!("{:?} must reject", state));
                assert!(
                    error.to_string().contains("Connection is closed"),
                    "{:?}: got {}",
                    state,
                    error
                );
            }
        }
    }
}

/// Blocking wrapper tests
#[cfg(test)]
mod blocking_tests {
    use super::*;

    #[test]
    fn test_session_type_alias_exists() {
        // Verify that Session is a type alias for Connection
        fn takes_session(_session: &Session) {}
        fn takes_connection(_connection: &Connection) {}

        // This should compile, showing Session = Connection
        fn verify_interchangeable<F1, F2>(f1: F1, f2: F2)
        where
            F1: Fn(&Session),
            F2: Fn(&Connection),
        {
            let _ = (f1, f2);
        }

        verify_interchangeable(takes_session, takes_connection);
    }

    #[test]
    fn test_blocking_runtime_exists() {
        // Verify that blocking_runtime() function exists and returns a Runtime
        let runtime = blocking_runtime();
        // If this compiles, the runtime is valid
        let _ = runtime.handle();
    }

    #[test]
    fn test_connection_has_blocking_import_csv() {
        // This test verifies the blocking_import_csv_from_file method exists
        // by checking the method signature compiles
        fn _check_method_exists(_conn: &mut Connection) {
            // Method signature check - will fail to compile if method doesn't exist
            let _: fn(
                &mut Connection,
                &str,
                &std::path::Path,
                crate::import::csv::CsvImportOptions,
            ) -> Result<u64, crate::import::ImportError> =
                Connection::blocking_import_csv_from_file;
        }
    }

    #[test]
    fn test_connection_has_blocking_import_parquet() {
        fn _check_method_exists(_conn: &mut Connection) {
            let _: fn(
                &mut Connection,
                &str,
                &std::path::Path,
                crate::import::parquet::ParquetImportOptions,
            ) -> Result<u64, crate::import::ImportError> = Connection::blocking_import_from_parquet;
        }
    }

    #[test]
    fn test_connection_has_blocking_import_record_batch() {
        fn _check_method_exists(_conn: &mut Connection) {
            let _: fn(
                &mut Connection,
                &str,
                &RecordBatch,
                crate::import::arrow::ArrowImportOptions,
            ) -> Result<u64, crate::import::ImportError> =
                Connection::blocking_import_from_record_batch;
        }
    }

    #[test]
    fn test_connection_has_blocking_import_arrow_ipc() {
        fn _check_method_exists(_conn: &mut Connection) {
            let _: fn(
                &mut Connection,
                &str,
                &std::path::Path,
                crate::import::arrow::ArrowImportOptions,
            ) -> Result<u64, crate::import::ImportError> =
                Connection::blocking_import_from_arrow_ipc;
        }
    }

    #[test]
    fn test_connection_has_blocking_export_csv() {
        fn _check_method_exists(_conn: &mut Connection) {
            let _: fn(
                &mut Connection,
                crate::query::export::ExportSource,
                &std::path::Path,
                crate::export::csv::CsvExportOptions,
            ) -> Result<u64, crate::export::csv::ExportError> =
                Connection::blocking_export_csv_to_file;
        }
    }

    #[test]
    fn test_connection_has_blocking_export_parquet() {
        fn _check_method_exists(_conn: &mut Connection) {
            let _: fn(
                &mut Connection,
                crate::query::export::ExportSource,
                &std::path::Path,
                crate::export::parquet::ParquetExportOptions,
            ) -> Result<u64, crate::export::csv::ExportError> =
                Connection::blocking_export_to_parquet;
        }
    }

    #[test]
    fn test_connection_has_blocking_export_record_batches() {
        fn _check_method_exists(_conn: &mut Connection) {
            let _: fn(
                &mut Connection,
                crate::query::export::ExportSource,
                crate::export::arrow::ArrowExportOptions,
            ) -> Result<Vec<RecordBatch>, crate::export::csv::ExportError> =
                Connection::blocking_export_to_record_batches;
        }
    }

    #[test]
    fn test_connection_has_blocking_export_arrow_ipc() {
        fn _check_method_exists(_conn: &mut Connection) {
            let _: fn(
                &mut Connection,
                crate::query::export::ExportSource,
                &std::path::Path,
                crate::export::arrow::ArrowExportOptions,
            ) -> Result<u64, crate::export::csv::ExportError> =
                Connection::blocking_export_to_arrow_ipc;
        }
    }

    #[test]
    fn test_connection_has_supports_native_parquet_import() {
        // Verify that supports_native_parquet_import exists and has the correct signature.
        fn _check_method_exists(_conn: &Connection) {
            let _: fn(&Connection) -> bool = Connection::supports_native_parquet_import;
        }
    }

    #[test]
    fn test_connection_has_import_from_parquet_stream() {
        // Verify that import_from_parquet_stream is wired (async, takes reader).
        // The function pointer syntax is not straightforward for async methods, so
        // we verify by name resolution only.
        fn _check_exists<R: tokio::io::AsyncRead + Unpin + Send + 'static>(
            _conn: &mut Connection,
            _table: &str,
            _reader: R,
            _opts: crate::import::parquet::ParquetImportOptions,
        ) {
            // If this compiles, the method exists with the correct type parameters.
        }
    }

    #[test]
    fn test_resolve_native_parquet_uses_override_when_set() {
        // Verify that ParquetImportOptions.native_parquet_override propagates correctly.
        // We test the options type directly since Connection requires a live database.
        let opts_force_native =
            crate::import::parquet::ParquetImportOptions::default().with_native_parquet(Some(true));
        assert_eq!(
            opts_force_native.native_parquet_override,
            Some(true),
            "Override Some(true) should be stored"
        );

        let opts_force_csv = crate::import::parquet::ParquetImportOptions::default()
            .with_native_parquet(Some(false));
        assert_eq!(
            opts_force_csv.native_parquet_override,
            Some(false),
            "Override Some(false) should be stored"
        );

        let opts_auto = crate::import::parquet::ParquetImportOptions::default();
        assert_eq!(
            opts_auto.native_parquet_override, None,
            "Default should be None (auto-detect)"
        );
    }
}