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
//! 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, SessionState};
use crate::error::{ConnectionError, ExasolError, QueryError};
use crate::query::prepared::PreparedStatement;
use crate::query::results::ResultSet;
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;
use tokio::time::timeout;
/// 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;
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.
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());
let session_info = transport
.authenticate(&credentials)
.await
.map_err(|e| ConnectionError::AuthenticationFailed(e.to_string()))?;
// Create session config from connection params
let session_config = SessionConfig {
idle_timeout: params.idle_timeout,
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,
};
// If the URI carried a schema, activate it server-side so unqualified
// queries work without a follow-up `set_schema()` call. On failure we
// must close the transport (we are already authenticated server-side)
// before propagating the error — returning a half-open `Connection`
// whose session state silently disagrees with the URI is worse than a
// clear error.
if let Some(schema_name) = schema {
if let Err(query_err) = connection.set_schema(schema_name.clone()).await {
let host = connection.params.host.clone();
let port = connection.params.port;
let _ = connection.shutdown().await;
return Err(ConnectionError::ConnectionFailed {
host,
port,
message: format!(
"failed to activate schema '{}' from connection URI: {}",
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 {
Statement::new(sql)
}
// ========================================================================
// 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()))?;
// Update session state
self.session.set_state(SessionState::Executing).await;
// Increment query counter
self.session.increment_query_count();
// Build final SQL with parameters
let final_sql = stmt.build_sql()?;
// Execute with timeout
let timeout_duration = Duration::from_millis(stmt.timeout_ms());
let transport = Arc::clone(&self.transport);
let result = timeout(timeout_duration, async move {
let mut transport_guard = transport.lock().await;
transport_guard.execute_query(&final_sql).await
})
.await
.map_err(|_| QueryError::Timeout {
timeout_ms: stmt.timeout_ms(),
})?
.map_err(|e| QueryError::ExecutionFailed(e.to_string()))?;
// Update session state back to ready/in_transaction
self.update_session_state_after_query().await;
// 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()))?;
// Update session state
self.session.set_state(SessionState::Executing).await;
// 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);
// Update session state back to ready/in_transaction
self.update_session_state_after_query().await;
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()))?;
// Update session state
self.session.set_state(SessionState::Executing).await;
// 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);
// Update session state back to ready/in_transaction
self.update_session_state_after_query().await;
match result {
QueryResult::RowCount { count } => Ok(count),
QueryResult::ResultSet { .. } => Err(QueryError::UnexpectedResultSet),
}
}
/// 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
// ========================================================================
pub async fn begin_transaction(&mut self) -> Result<(), QueryError> {
// 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
// ========================================================================
/// Get the current schema.
///
/// # Returns
///
/// The current schema name, or `None` if no schema is set.
pub async fn current_schema(&self) -> Option<String> {
self.session.current_schema().await
}
/// Set the current schema.
///
/// # Arguments
///
/// * `schema` - The schema name to set
///
/// # Errors
///
/// Returns `QueryError` if the operation fails.
///
/// # Example
///
pub async fn set_schema(&mut self, schema: impl Into<String>) -> Result<(), QueryError> {
let schema_name = schema.into();
self.execute_update(format!("OPEN SCHEMA {}", schema_name))
.await?;
self.session.set_current_schema(Some(schema_name)).await;
Ok(())
}
// ========================================================================
// 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.
///
/// # Returns
///
/// `true` if the connection is closed, `false` otherwise.
pub async fn is_closed(&self) -> bool {
self.session.is_closed().await
}
/// 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.
///
/// # 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. The entire stream is buffered into memory because
/// Parquet requires random access to read file metadata.
///
/// When the connected server supports native Parquet import (Exasol 2025.1.11+),
/// the buffered bytes are forwarded directly without CSV conversion.
///
/// # 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.
///
/// This method converts each Parquet file to CSV format concurrently,
/// then streams the data through parallel HTTP transport connections.
///
/// 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.
///
/// This method exports data from the specified source to a Parquet file.
/// The data is first received as CSV from Exasol, then converted to Parquet format.
///
/// # 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 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.
///
/// # 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.
///
/// # 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.
///
/// # 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.
///
/// # 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))
}
// ========================================================================
// Private Helper Methods
// ========================================================================
/// Update session state after query execution.
async fn update_session_state_after_query(&self) {
if self.session.in_transaction() {
self.session.set_state(SessionState::InTransaction).await;
} else {
self.session.set_state(SessionState::Ready).await;
}
self.session.update_activity().await;
}
}
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
}
/// 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 test_connection_builder() {
let _builder = ConnectionBuilder::new()
.host("localhost")
.port(8563)
.username("test")
.password("secret")
.schema("MY_SCHEMA")
.use_tls(false);
// Builder should compile and be valid
// Actual connection requires a running Exasol instance
}
#[test]
fn test_create_statement_is_sync() {
// This test verifies that create_statement is synchronous
// by calling it without await
// Note: We can't actually create a Connection without a database,
// but we can verify the API compiles correctly
}
}
/// 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)"
);
}
}