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
//! Client configuration.
//!
//! Supporting types (`RedirectConfig`, `TimeoutConfig`, `RetryPolicy`) live in
//! the `types` submodule and are re-exported here for convenience.
mod types;
pub use types::*;
use std::time::Duration;
use mssql_auth::Credentials;
#[cfg(feature = "tls")]
use mssql_tls::TlsConfig;
use tds_protocol::version::TdsVersion;
/// Parse a boolean value from a connection string keyword.
///
/// Per the ADO.NET specification, boolean keywords accept:
/// `true`, `false`, `yes`, `no`, `1`, `0` (case-insensitive).
/// Returns an error for any other value, preventing silent misconfiguration.
fn parse_conn_bool(key: &str, value: &str) -> Result<bool, crate::error::Error> {
match value.to_lowercase().as_str() {
"true" | "yes" | "1" => Ok(true),
"false" | "no" | "0" => Ok(false),
_ => Err(crate::error::Error::Config(format!(
"invalid boolean value for '{key}': '{value}' (expected true/false/yes/no/1/0)"
))),
}
}
/// Split a connection string into key-value pairs, respecting quoted values.
///
/// Per the ADO.NET specification:
/// - Values containing semicolons must be enclosed in double (`"`) or single (`'`) quotes
/// - Doubled quotes inside are escapes: `""` → `"`, `''` → `'`
/// - Leading/trailing whitespace around values is trimmed (but preserved inside quotes)
///
/// Returns pairs of `(key, value)` where the value has quotes stripped and escapes resolved.
fn split_connection_string(conn_str: &str) -> Result<Vec<(String, String)>, crate::error::Error> {
let mut pairs = Vec::new();
let chars: Vec<char> = conn_str.chars().collect();
let len = chars.len();
let mut i = 0;
while i < len {
// Skip whitespace and semicolons between pairs
while i < len && (chars[i] == ';' || chars[i].is_whitespace()) {
i += 1;
}
if i >= len {
break;
}
// Read key (up to '=')
let key_start = i;
while i < len && chars[i] != '=' {
i += 1;
}
if i >= len {
// Trailing text with no '=' — skip it (could be trailing whitespace)
let remaining = chars[key_start..].iter().collect::<String>();
if remaining.trim().is_empty() {
break;
}
return Err(crate::error::Error::Config(format!(
"invalid key-value pair (missing '='): '{remaining}'"
)));
}
let key: String = chars[key_start..i].iter().collect();
i += 1; // skip '='
// Read value — may be quoted or unquoted
// Skip leading whitespace in value
while i < len && chars[i].is_whitespace() {
i += 1;
}
let value = if i < len && (chars[i] == '"' || chars[i] == '\'') {
// Quoted value: read until matching unescaped closing quote
let quote_char = chars[i];
i += 1; // skip opening quote
let mut val = String::new();
loop {
if i >= len {
return Err(crate::error::Error::Config(format!(
"unterminated quoted value for key '{}'",
key.trim()
)));
}
if chars[i] == quote_char {
// Check for escaped quote (doubled: "" or '')
if i + 1 < len && chars[i + 1] == quote_char {
val.push(quote_char);
i += 2;
} else {
i += 1; // skip closing quote
break;
}
} else {
val.push(chars[i]);
i += 1;
}
}
// Skip to next semicolon or end
while i < len && chars[i] != ';' {
i += 1;
}
val
} else {
// Unquoted value: read until semicolon or end
let val_start = i;
while i < len && chars[i] != ';' {
i += 1;
}
chars[val_start..i].iter().collect::<String>()
};
let key_trimmed = key.trim().to_string();
if !key_trimmed.is_empty() {
pairs.push((key_trimmed, value));
}
}
Ok(pairs)
}
/// Convert a connection string value to `Option<String>`, treating empty strings as `None`.
///
/// In ADO.NET, specifying a keyword with an empty value (e.g., `Database=;`) resets it
/// to its default. We represent this as `None` for optional fields.
fn non_empty(value: &str) -> Option<String> {
if value.is_empty() {
None
} else {
Some(value.to_string())
}
}
/// Configuration for connecting to SQL Server.
///
/// This struct is marked `#[non_exhaustive]` to allow adding new fields
/// in future releases without breaking semver. Use [`Config::default()`]
/// or [`Config::from_connection_string()`] to construct instances.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Config {
/// Server hostname or IP address.
pub host: String,
/// Server port (default: 1433).
pub port: u16,
/// Database name.
pub database: Option<String>,
/// Authentication credentials.
pub credentials: Credentials,
/// TLS configuration (only available when `tls` feature is enabled).
#[cfg(feature = "tls")]
pub tls: TlsConfig,
/// Application name (shown in SQL Server management tools).
pub application_name: String,
/// Connection timeout.
pub connect_timeout: Duration,
/// Command timeout.
pub command_timeout: Duration,
/// TDS packet size.
pub packet_size: u16,
/// Whether to use TDS 8.0 strict mode.
pub strict_mode: bool,
/// Whether to trust the server certificate.
pub trust_server_certificate: bool,
/// Instance name (for named instances).
pub instance: Option<String>,
/// Whether to enable MARS (Multiple Active Result Sets).
pub mars: bool,
/// Whether to require encryption (TLS).
/// When true, the connection will use TLS even if the server doesn't require it.
/// When false, encryption is used only if the server requires it.
pub encrypt: bool,
/// Disable TLS entirely and connect with plaintext.
///
/// **⚠️ SECURITY WARNING:** This completely disables TLS/SSL encryption.
/// Credentials and data will be transmitted in plaintext. Only use this
/// for development/testing on trusted networks with legacy SQL Server
/// instances that don't support modern TLS versions.
///
/// This option exists for compatibility with legacy SQL Server versions
/// (2008 and earlier) that may only support TLS 1.0/1.1, which modern
/// TLS libraries (like rustls) don't support for security reasons.
///
/// When `true`:
/// - Overrides the `encrypt` setting
/// - Sends `ENCRYPT_NOT_SUP` in PreLogin
/// - No TLS handshake occurs
/// - All traffic including login credentials is unencrypted
///
/// **Do not use in production without understanding the security implications.**
pub no_tls: bool,
/// Redirect handling configuration (for Azure SQL).
pub redirect: RedirectConfig,
/// Retry policy for transient error handling.
pub retry: RetryPolicy,
/// Timeout configuration for various connection phases.
pub timeouts: TimeoutConfig,
/// Requested TDS protocol version.
///
/// This specifies which TDS protocol version to request during connection.
/// The server may negotiate a lower version if it doesn't support the requested version.
///
/// Supported versions:
/// - `TdsVersion::V7_3A` - SQL Server 2008
/// - `TdsVersion::V7_3B` - SQL Server 2008 R2
/// - `TdsVersion::V7_4` - SQL Server 2012+ (default)
/// - `TdsVersion::V8_0` - SQL Server 2022+ strict mode (requires `strict_mode = true`)
///
/// Note: When `strict_mode` is enabled, this is ignored and TDS 8.0 is used.
pub tds_version: TdsVersion,
/// Application workload intent for AlwaysOn Availability Group routing.
///
/// When set to [`ApplicationIntent::ReadOnly`], SQL Server routes the
/// connection to a readable secondary replica. Sent in LOGIN7 TypeFlags
/// as the `READONLY_INTENT` bit.
pub application_intent: ApplicationIntent,
/// Client workstation name sent to SQL Server in the LOGIN7 HostName field.
///
/// Used for auditing via `sys.dm_exec_sessions.host_name`.
/// When `None`, the driver sends the machine hostname (from the `COMPUTERNAME`
/// or `HOSTNAME` environment variable). Set via `Workstation ID` or `WSID`
/// in connection strings.
pub workstation_id: Option<String>,
/// Session language for server warning/error messages.
///
/// When set, sent in LOGIN7's Language field. The language name can be
/// up to 128 characters. Set via `Language` or `Current Language` in
/// connection strings.
pub language: Option<String>,
/// Enable MultiSubnetFailover for AlwaysOn Availability Group listeners.
///
/// When `true`, the driver resolves the server hostname to all IP addresses
/// and attempts parallel TCP connections simultaneously. The first successful
/// connection wins and all others are cancelled. This reduces connection time
/// when the AG listener spans multiple subnets.
///
/// Set via `MultiSubnetFailover=True` in connection strings.
///
/// Default: `false`
pub multi_subnet_failover: bool,
/// Whether to send `String`/`&str` parameters as NVARCHAR (Unicode).
///
/// When `true` (default), string parameters are sent as NVARCHAR using
/// UTF-16LE encoding. This is safe for all character sets but prevents
/// SQL Server from using index seeks on VARCHAR columns (due to implicit
/// NVARCHAR→VARCHAR conversion).
///
/// When `false`, string parameters are sent as VARCHAR using Windows-1252
/// encoding. This allows index seeks on VARCHAR columns but may lose data
/// for characters outside the Windows-1252 range.
///
/// Set via `SendStringParametersAsUnicode=false` in connection strings.
///
/// Default: `true`
pub send_string_parameters_as_unicode: bool,
/// Always Encrypted configuration.
///
/// When `Some`, the client will negotiate Always Encrypted support with the
/// server and transparently decrypt encrypted column values in result sets.
///
/// Set via `Column Encryption Setting=Enabled` in connection strings, or
/// programmatically via [`Config::with_column_encryption`].
///
/// Wrapped in `Arc` because `EncryptionConfig` contains trait objects (key store
/// providers) which cannot implement `Clone`. The `Arc` allows `Config` to remain
/// `Clone` while sharing the encryption configuration.
#[cfg(feature = "always-encrypted")]
pub column_encryption: Option<std::sync::Arc<crate::encryption::EncryptionConfig>>,
}
impl Default for Config {
fn default() -> Self {
let timeouts = TimeoutConfig::default();
Self {
host: "localhost".to_string(),
port: 1433,
database: None,
credentials: Credentials::sql_server("", ""),
#[cfg(feature = "tls")]
tls: TlsConfig::default(),
application_name: "mssql-client".to_string(),
connect_timeout: timeouts.connect_timeout,
command_timeout: timeouts.command_timeout,
packet_size: 4096,
strict_mode: false,
trust_server_certificate: false,
instance: None,
mars: false,
encrypt: true, // Default to encrypted for security
no_tls: false, // Never plaintext by default
redirect: RedirectConfig::default(),
retry: RetryPolicy::default(),
timeouts,
tds_version: TdsVersion::V7_4, // Default to TDS 7.4 for broad compatibility
application_intent: ApplicationIntent::default(),
workstation_id: None,
language: None,
multi_subnet_failover: false,
send_string_parameters_as_unicode: true,
#[cfg(feature = "always-encrypted")]
column_encryption: None,
}
}
}
impl Config {
/// Create a new configuration with default values.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Parse a connection string into configuration.
///
/// Supports ADO.NET-style connection strings with full quoting support:
/// ```text
/// Server=localhost;Database=mydb;User Id=sa;Password="complex;pass";
/// ```
///
/// Values containing semicolons can be enclosed in double or single quotes
/// per the ADO.NET specification. The `tcp:` prefix from Azure Portal
/// connection strings is automatically stripped.
pub fn from_connection_string(conn_str: &str) -> Result<Self, crate::error::Error> {
let mut config = Self::default();
let pairs = split_connection_string(conn_str)?;
for (key, value) in &pairs {
let key = key.trim().to_lowercase();
let value = value.trim();
match key.as_str() {
// --- Server / Data Source (ADO.NET aliases: Addr, Address, Network Address) ---
"server" | "data source" | "addr" | "address" | "network address" | "host" => {
// Strip tcp: prefix (common in Azure Portal connection strings).
// Reject np: (Named Pipes) and lpc: (Shared Memory) — not supported.
// All prefix checks are case-insensitive per ADO.NET conventions.
let lower_value = value.to_lowercase();
let server_value = if lower_value.starts_with("tcp:") {
&value[4..]
} else if lower_value.starts_with("np:") {
return Err(crate::error::Error::Config(
"Named Pipes connections (np:) are not supported. Use TCP connections instead."
.into(),
));
} else if lower_value.starts_with("lpc:") {
return Err(crate::error::Error::Config(
"Shared Memory connections (lpc:) are not supported. Use TCP connections instead."
.into(),
));
} else {
value
};
// Handle host,port or host\instance format
if let Some((host, port_or_instance)) = server_value.split_once(',') {
config.host = host.to_string();
config.port = port_or_instance.trim().parse().map_err(|_| {
crate::error::Error::Config(format!("invalid port: {port_or_instance}"))
})?;
} else if let Some((host, instance)) = server_value.split_once('\\') {
config.host = host.to_string();
config.instance = non_empty(instance);
} else {
config.host = server_value.to_string();
}
}
"port" => {
config.port = value.parse().map_err(|_| {
crate::error::Error::Config(format!("invalid port: {value}"))
})?;
}
// --- Database ---
"database" | "initial catalog" => {
config.database = non_empty(value);
}
// --- Credentials ---
"user id" | "uid" | "user" => {
if let Credentials::SqlServer { password, .. } = &config.credentials {
config.credentials =
Credentials::sql_server(value.to_string(), password.clone());
}
}
"password" | "pwd" => {
if let Credentials::SqlServer { username, .. } = &config.credentials {
config.credentials =
Credentials::sql_server(username.clone(), value.to_string());
}
}
// --- Application ---
"application name" | "app" => {
config.application_name = value.to_string();
}
"applicationintent" | "application intent" => {
config.application_intent = match value.to_lowercase().as_str() {
"readonly" => ApplicationIntent::ReadOnly,
"readwrite" => ApplicationIntent::ReadWrite,
_ => {
return Err(crate::error::Error::Config(format!(
"invalid ApplicationIntent: '{value}' (expected ReadOnly or ReadWrite)"
)));
}
};
}
"workstation id" | "wsid" => {
config.workstation_id = non_empty(value);
}
"current language" | "language" => {
config.language = non_empty(value);
}
// --- Timeouts (ADO.NET alias: Timeout) ---
"connect timeout" | "connection timeout" | "timeout" => {
let secs: u64 = value.parse().map_err(|_| {
crate::error::Error::Config(format!("invalid timeout: {value}"))
})?;
config.connect_timeout = Duration::from_secs(secs);
}
"command timeout" => {
let secs: u64 = value.parse().map_err(|_| {
crate::error::Error::Config(format!("invalid timeout: {value}"))
})?;
config.command_timeout = Duration::from_secs(secs);
}
// --- Security ---
"trustservercertificate" | "trust server certificate" => {
config.trust_server_certificate = parse_conn_bool(&key, value)?;
}
"encrypt" => {
// Encrypt supports several non-boolean values beyond true/false:
// - "strict" = TDS 8.0 strict mode (always encrypted transport)
// - "mandatory" / "true" / "yes" / "1" = require TLS
// - "optional" / "false" / "no" / "0" = TLS only if server requires
// - "no_tls" = Tiberius-compatible plaintext mode for legacy servers
//
// "mandatory" and "optional" are Microsoft.Data.SqlClient v5+ aliases.
if value.eq_ignore_ascii_case("strict") {
config.strict_mode = true;
config.encrypt = true;
config.no_tls = false;
} else if value.eq_ignore_ascii_case("mandatory") {
config.encrypt = true;
config.no_tls = false;
} else if value.eq_ignore_ascii_case("optional") {
config.encrypt = false;
config.no_tls = false;
} else if value.eq_ignore_ascii_case("no_tls") {
config.no_tls = true;
config.encrypt = false;
} else {
// Standard boolean values (true/false/yes/no/1/0)
let enabled = parse_conn_bool(&key, value)?;
config.encrypt = enabled;
config.no_tls = false;
}
}
"integrated security" | "trusted_connection" => {
// Accepts standard booleans + "sspi" (ADO.NET strongly-recommended value)
let enabled =
value.eq_ignore_ascii_case("sspi") || parse_conn_bool(&key, value)?;
if enabled {
#[cfg(any(feature = "integrated-auth", feature = "sspi-auth"))]
{
config.credentials = Credentials::Integrated;
}
#[cfg(not(any(feature = "integrated-auth", feature = "sspi-auth")))]
{
return Err(crate::error::Error::Config(
"Integrated Security requires the 'integrated-auth' (Linux/macOS) \
or 'sspi-auth' (Windows) feature to be enabled"
.into(),
));
}
}
}
// --- Always Encrypted ---
"column encryption setting" | "columnencryptionsetting" => {
#[cfg(feature = "always-encrypted")]
if value.eq_ignore_ascii_case("enabled") {
config.column_encryption = Some(std::sync::Arc::new(
crate::encryption::EncryptionConfig::new(),
));
}
#[cfg(not(feature = "always-encrypted"))]
if value.eq_ignore_ascii_case("enabled") {
return Err(crate::error::Error::Config(
"Column Encryption Setting=Enabled requires the 'always-encrypted' feature. \
Enable it in your Cargo.toml: mssql-client = { features = [\"always-encrypted\"] }"
.to_string(),
));
}
}
// --- Protocol ---
"multipleactiveresultsets" | "mars" => {
config.mars = parse_conn_bool(&key, value)?;
}
"packet size" => {
config.packet_size = value.parse().map_err(|_| {
crate::error::Error::Config(format!("invalid packet size: {value}"))
})?;
}
"tdsversion" | "tds version" | "protocolversion" | "protocol version" => {
config.tds_version = TdsVersion::parse(value).ok_or_else(|| {
crate::error::Error::Config(format!(
"invalid TDS version: {value}. Supported values: 7.3, 7.3A, 7.3B, 7.4, 8.0"
))
})?;
if config.tds_version.is_tds_8() {
config.strict_mode = true;
}
}
// --- Connection resiliency ---
"connectretrycount" | "connect retry count" => {
config.retry.max_retries = value.parse().map_err(|_| {
crate::error::Error::Config(format!("invalid ConnectRetryCount: '{value}'"))
})?;
}
"connectretryinterval" | "connect retry interval" => {
let secs: u64 = value.parse().map_err(|_| {
crate::error::Error::Config(format!(
"invalid ConnectRetryInterval: '{value}'"
))
})?;
config.retry.initial_backoff = Duration::from_secs(secs);
}
// --- Pool keywords: recognized but must be set via PoolConfig ---
"max pool size"
| "min pool size"
| "pooling"
| "connection lifetime"
| "load balance timeout" => {
tracing::info!(
key = key.as_str(),
value = value,
"connection string keyword '{}' is recognized but pool settings \
must be configured via PoolConfig, not the connection string",
key,
);
}
// --- MultiSubnetFailover ---
"multisubnetfailover" | "multi subnet failover" => {
config.multi_subnet_failover = parse_conn_bool(&key, value)?;
}
// --- String parameter encoding ---
"sendstringparametersasunicode" | "send string parameters as unicode" => {
config.send_string_parameters_as_unicode = parse_conn_bool(&key, value)?;
}
// --- Known ADO.NET keywords not supported by this driver ---
"failover partner"
| "persist security info"
| "persistsecurityinfo"
| "enlist"
| "replication"
| "transaction binding"
| "type system version"
| "user instance"
| "attachdbfilename"
| "extended properties"
| "initial file name"
| "context connection"
| "network library"
| "network"
| "net"
| "asynchronous processing"
| "async"
| "transparentnetworkipresolution"
| "poolblockingperiod"
| "authentication"
| "hostnameincertificate"
| "servercertificate" => {
tracing::info!(
key = key.as_str(),
value = value,
"connection string keyword '{}' is recognized but not supported by this driver",
key,
);
}
_ => {
tracing::debug!(
key = key.as_str(),
value = value,
"ignoring unknown connection string option"
);
}
}
}
Ok(config)
}
/// Set the server host.
#[must_use]
pub fn host(mut self, host: impl Into<String>) -> Self {
self.host = host.into();
self
}
/// Set the server port.
#[must_use]
pub fn port(mut self, port: u16) -> Self {
self.port = port;
self
}
/// Set the database name.
#[must_use]
pub fn database(mut self, database: impl Into<String>) -> Self {
self.database = Some(database.into());
self
}
/// Set the credentials.
#[must_use]
pub fn credentials(mut self, credentials: Credentials) -> Self {
self.credentials = credentials;
self
}
/// Set the application name.
#[must_use]
pub fn application_name(mut self, name: impl Into<String>) -> Self {
self.application_name = name.into();
self
}
/// Set the connect timeout.
#[must_use]
pub fn connect_timeout(mut self, timeout: Duration) -> Self {
self.connect_timeout = timeout;
self
}
/// Set trust server certificate option.
#[must_use]
pub fn trust_server_certificate(mut self, trust: bool) -> Self {
self.trust_server_certificate = trust;
#[cfg(feature = "tls")]
{
self.tls = self.tls.trust_server_certificate(trust);
}
self
}
/// Enable TDS 8.0 strict mode.
#[must_use]
pub fn strict_mode(mut self, enabled: bool) -> Self {
self.strict_mode = enabled;
#[cfg(feature = "tls")]
{
self.tls = self.tls.strict_mode(enabled);
}
if enabled {
self.tds_version = TdsVersion::V8_0;
}
self
}
/// Set the TDS protocol version.
///
/// This specifies which TDS protocol version to request during connection.
/// The server may negotiate a lower version if it doesn't support the requested version.
///
/// # Examples
///
/// ```no_run
/// use mssql_client::Config;
/// use tds_protocol::version::TdsVersion;
///
/// // Connect to SQL Server 2008
/// let config = Config::new()
/// .host("legacy-server")
/// .tds_version(TdsVersion::V7_3A);
///
/// // Connect to SQL Server 2008 R2
/// let config = Config::new()
/// .host("legacy-server")
/// .tds_version(TdsVersion::V7_3B);
/// ```
///
/// Note: When `strict_mode` is enabled, this is ignored and TDS 8.0 is used.
#[must_use]
pub fn tds_version(mut self, version: TdsVersion) -> Self {
self.tds_version = version;
// If TDS 8.0 is requested, automatically enable strict mode
if version.is_tds_8() {
self.strict_mode = true;
#[cfg(feature = "tls")]
{
self.tls = self.tls.strict_mode(true);
}
}
self
}
/// Enable or disable TLS encryption.
///
/// When `true` (default), the connection will use TLS encryption.
/// When `false`, encryption is used only if the server requires it.
///
/// **Warning:** Disabling encryption is insecure and should only be
/// used for development/testing on trusted networks.
#[must_use]
pub fn encrypt(mut self, enabled: bool) -> Self {
self.encrypt = enabled;
self
}
/// Disable TLS entirely and connect with plaintext (Tiberius-compatible).
///
/// **⚠️ SECURITY WARNING:** This completely disables TLS/SSL encryption.
/// Credentials and all data will be transmitted in plaintext over the network.
///
/// # When to use this
///
/// This option exists for compatibility with legacy SQL Server versions
/// (2008 and earlier) that may only support TLS 1.0/1.1. Modern TLS libraries
/// like rustls require TLS 1.2 or higher for security reasons, making it
/// impossible to establish encrypted connections to these older servers.
///
/// # Security implications
///
/// When enabled:
/// - Login credentials are sent in plaintext
/// - All query data is transmitted without encryption
/// - Network traffic can be intercepted and read by attackers
///
/// **Only use this for development/testing on isolated, trusted networks.**
///
/// # Example
///
/// ```rust,ignore
/// // Connection string (Tiberius-compatible)
/// let config = Config::from_connection_string(
/// "Server=legacy-server;User Id=sa;Password=secret;Encrypt=no_tls"
/// )?;
///
/// // Builder API
/// let config = Config::new()
/// .host("legacy-server")
/// .no_tls(true);
/// ```
#[must_use]
pub fn no_tls(mut self, enabled: bool) -> Self {
self.no_tls = enabled;
if enabled {
self.encrypt = false;
}
self
}
/// Enable Always Encrypted with the given encryption configuration.
///
/// When enabled, the client will negotiate Always Encrypted support during
/// connection and transparently decrypt encrypted column values.
///
/// # Example
///
/// ```rust,ignore
/// use mssql_client::{Config, EncryptionConfig};
/// use mssql_auth::InMemoryKeyStore;
///
/// let config = Config::new()
/// .with_column_encryption(
/// EncryptionConfig::new().with_provider(key_store)
/// );
/// ```
#[cfg(feature = "always-encrypted")]
#[must_use]
pub fn with_column_encryption(mut self, config: crate::encryption::EncryptionConfig) -> Self {
self.column_encryption = Some(std::sync::Arc::new(config));
self
}
/// Create a new configuration with a different host (for routing).
#[must_use]
pub fn with_host(mut self, host: &str) -> Self {
self.host = host.to_string();
self
}
/// Create a new configuration with a different port (for routing).
#[must_use]
pub fn with_port(mut self, port: u16) -> Self {
self.port = port;
self
}
/// Set the redirect handling configuration.
#[must_use]
pub fn redirect(mut self, redirect: RedirectConfig) -> Self {
self.redirect = redirect;
self
}
/// Set the maximum number of redirect attempts.
#[must_use]
pub fn max_redirects(mut self, max: u8) -> Self {
self.redirect.max_redirects = max;
self
}
/// Set the retry policy for transient error handling.
#[must_use]
pub fn retry(mut self, retry: RetryPolicy) -> Self {
self.retry = retry;
self
}
/// Set the maximum number of retry attempts.
#[must_use]
pub fn max_retries(mut self, max: u32) -> Self {
self.retry.max_retries = max;
self
}
/// Set the timeout configuration.
#[must_use]
pub fn timeouts(mut self, timeouts: TimeoutConfig) -> Self {
// Sync the legacy fields for backward compatibility first
self.connect_timeout = timeouts.connect_timeout;
self.command_timeout = timeouts.command_timeout;
self.timeouts = timeouts;
self
}
/// Set the application workload intent for AlwaysOn AG routing.
#[must_use]
pub fn application_intent(mut self, intent: ApplicationIntent) -> Self {
self.application_intent = intent;
self
}
/// Set the client workstation name sent to SQL Server in LOGIN7.
///
/// This appears in `sys.dm_exec_sessions.host_name` for auditing.
/// When not set, the driver sends the machine hostname automatically.
#[must_use]
pub fn workstation_id(mut self, id: impl Into<String>) -> Self {
self.workstation_id = Some(id.into());
self
}
/// Set the session language for server messages.
///
/// The language name can be up to 128 characters (e.g., `"us_english"`).
#[must_use]
pub fn language(mut self, lang: impl Into<String>) -> Self {
self.language = Some(lang.into());
self
}
/// Enable MultiSubnetFailover for AlwaysOn Availability Group listeners.
///
/// When enabled, the driver resolves the server hostname to all IP addresses
/// and races parallel TCP connections. The first successful connection wins.
#[must_use]
pub fn multi_subnet_failover(mut self, enabled: bool) -> Self {
self.multi_subnet_failover = enabled;
self
}
/// Control whether string parameters are sent as NVARCHAR (Unicode) or VARCHAR.
///
/// When `false`, `String`/`&str` parameters are sent as VARCHAR using
/// Windows-1252 encoding, which allows SQL Server to use index seeks on
/// VARCHAR columns.
///
/// Default: `true` (NVARCHAR)
#[must_use]
pub fn send_string_parameters_as_unicode(mut self, enabled: bool) -> Self {
self.send_string_parameters_as_unicode = enabled;
self
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn test_connection_string_parsing() {
let config = Config::from_connection_string(
"Server=localhost;Database=test;User Id=sa;Password=secret;",
)
.unwrap();
assert_eq!(config.host, "localhost");
assert_eq!(config.database, Some("test".to_string()));
}
#[test]
fn test_connection_string_with_port() {
let config =
Config::from_connection_string("Server=localhost,1434;Database=test;").unwrap();
assert_eq!(config.host, "localhost");
assert_eq!(config.port, 1434);
}
#[test]
fn test_connection_string_with_instance() {
let config =
Config::from_connection_string("Server=localhost\\SQLEXPRESS;Database=test;").unwrap();
assert_eq!(config.host, "localhost");
assert_eq!(config.instance, Some("SQLEXPRESS".to_string()));
}
#[test]
fn test_connection_string_dot_instance() {
// "." is a standard ADO.NET alias for localhost
let config = Config::from_connection_string("Server=.\\SQLEXPRESS;Database=test;").unwrap();
assert_eq!(config.host, ".");
assert_eq!(config.instance, Some("SQLEXPRESS".to_string()));
}
#[test]
fn test_connection_string_local_instance() {
// "(local)" is a standard ADO.NET alias for localhost
let config =
Config::from_connection_string("Server=(local)\\SQLEXPRESS;Database=test;").unwrap();
assert_eq!(config.host, "(local)");
assert_eq!(config.instance, Some("SQLEXPRESS".to_string()));
}
#[test]
fn test_redirect_config_defaults() {
let config = RedirectConfig::default();
assert_eq!(config.max_redirects, 2);
assert!(config.follow_redirects);
}
#[test]
fn test_redirect_config_builder() {
let config = RedirectConfig::new()
.max_redirects(5)
.follow_redirects(false);
assert_eq!(config.max_redirects, 5);
assert!(!config.follow_redirects);
}
#[test]
fn test_redirect_config_no_follow() {
let config = RedirectConfig::no_follow();
assert_eq!(config.max_redirects, 0);
assert!(!config.follow_redirects);
}
#[test]
fn test_config_redirect_builder() {
let config = Config::new().max_redirects(3);
assert_eq!(config.redirect.max_redirects, 3);
let config2 = Config::new().redirect(RedirectConfig::no_follow());
assert!(!config2.redirect.follow_redirects);
}
#[test]
fn test_retry_policy_defaults() {
let policy = RetryPolicy::default();
assert_eq!(policy.max_retries, 3);
assert_eq!(policy.initial_backoff, Duration::from_millis(100));
assert_eq!(policy.max_backoff, Duration::from_secs(30));
assert!((policy.backoff_multiplier - 2.0).abs() < f64::EPSILON);
assert!(policy.jitter);
}
#[test]
fn test_retry_policy_builder() {
let policy = RetryPolicy::new()
.max_retries(5)
.initial_backoff(Duration::from_millis(200))
.max_backoff(Duration::from_secs(60))
.backoff_multiplier(3.0)
.jitter(false);
assert_eq!(policy.max_retries, 5);
assert_eq!(policy.initial_backoff, Duration::from_millis(200));
assert_eq!(policy.max_backoff, Duration::from_secs(60));
assert!((policy.backoff_multiplier - 3.0).abs() < f64::EPSILON);
assert!(!policy.jitter);
}
#[test]
fn test_retry_policy_no_retry() {
let policy = RetryPolicy::no_retry();
assert_eq!(policy.max_retries, 0);
assert!(!policy.should_retry(0));
}
#[test]
fn test_retry_policy_should_retry() {
let policy = RetryPolicy::new().max_retries(3);
assert!(policy.should_retry(0));
assert!(policy.should_retry(1));
assert!(policy.should_retry(2));
assert!(!policy.should_retry(3));
assert!(!policy.should_retry(4));
}
#[test]
fn test_retry_policy_backoff_calculation() {
let policy = RetryPolicy::new()
.initial_backoff(Duration::from_millis(100))
.backoff_multiplier(2.0)
.max_backoff(Duration::from_secs(10))
.jitter(false);
assert_eq!(policy.backoff_for_attempt(0), Duration::ZERO);
assert_eq!(policy.backoff_for_attempt(1), Duration::from_millis(100));
assert_eq!(policy.backoff_for_attempt(2), Duration::from_millis(200));
assert_eq!(policy.backoff_for_attempt(3), Duration::from_millis(400));
}
#[test]
fn test_retry_policy_backoff_capped() {
let policy = RetryPolicy::new()
.initial_backoff(Duration::from_secs(1))
.backoff_multiplier(10.0)
.max_backoff(Duration::from_secs(5))
.jitter(false);
// Attempt 3 would be 1s * 10^2 = 100s, but capped at 5s
assert_eq!(policy.backoff_for_attempt(3), Duration::from_secs(5));
}
#[test]
fn test_config_retry_builder() {
let config = Config::new().max_retries(5);
assert_eq!(config.retry.max_retries, 5);
let config2 = Config::new().retry(RetryPolicy::no_retry());
assert_eq!(config2.retry.max_retries, 0);
}
#[test]
fn test_timeout_config_defaults() {
let config = TimeoutConfig::default();
assert_eq!(config.connect_timeout, Duration::from_secs(15));
assert_eq!(config.tls_timeout, Duration::from_secs(10));
assert_eq!(config.login_timeout, Duration::from_secs(30));
assert_eq!(config.command_timeout, Duration::from_secs(30));
assert_eq!(config.idle_timeout, Duration::from_secs(300));
assert_eq!(config.keepalive_interval, Some(Duration::from_secs(30)));
}
#[test]
fn test_timeout_config_builder() {
let config = TimeoutConfig::new()
.connect_timeout(Duration::from_secs(5))
.tls_timeout(Duration::from_secs(3))
.login_timeout(Duration::from_secs(10))
.command_timeout(Duration::from_secs(60))
.idle_timeout(Duration::from_secs(600))
.keepalive_interval(Some(Duration::from_secs(60)));
assert_eq!(config.connect_timeout, Duration::from_secs(5));
assert_eq!(config.tls_timeout, Duration::from_secs(3));
assert_eq!(config.login_timeout, Duration::from_secs(10));
assert_eq!(config.command_timeout, Duration::from_secs(60));
assert_eq!(config.idle_timeout, Duration::from_secs(600));
assert_eq!(config.keepalive_interval, Some(Duration::from_secs(60)));
}
#[test]
fn test_timeout_config_no_keepalive() {
let config = TimeoutConfig::new().no_keepalive();
assert_eq!(config.keepalive_interval, None);
}
#[test]
fn test_timeout_config_total_connect() {
let config = TimeoutConfig::new()
.connect_timeout(Duration::from_secs(5))
.tls_timeout(Duration::from_secs(3))
.login_timeout(Duration::from_secs(10));
// 5 + 3 + 10 = 18 seconds
assert_eq!(config.total_connect_timeout(), Duration::from_secs(18));
}
#[test]
fn test_config_timeouts_builder() {
let timeouts = TimeoutConfig::new()
.connect_timeout(Duration::from_secs(5))
.command_timeout(Duration::from_secs(60));
let config = Config::new().timeouts(timeouts);
assert_eq!(config.timeouts.connect_timeout, Duration::from_secs(5));
assert_eq!(config.timeouts.command_timeout, Duration::from_secs(60));
// Check that legacy fields are synced
assert_eq!(config.connect_timeout, Duration::from_secs(5));
assert_eq!(config.command_timeout, Duration::from_secs(60));
}
#[test]
fn test_tds_version_default() {
let config = Config::default();
assert_eq!(config.tds_version, TdsVersion::V7_4);
assert!(!config.strict_mode);
}
#[test]
fn test_tds_version_builder() {
let config = Config::new().tds_version(TdsVersion::V7_3A);
assert_eq!(config.tds_version, TdsVersion::V7_3A);
assert!(!config.strict_mode);
let config = Config::new().tds_version(TdsVersion::V7_3B);
assert_eq!(config.tds_version, TdsVersion::V7_3B);
assert!(!config.strict_mode);
// TDS 8.0 should automatically enable strict mode
let config = Config::new().tds_version(TdsVersion::V8_0);
assert_eq!(config.tds_version, TdsVersion::V8_0);
assert!(config.strict_mode);
}
#[test]
fn test_strict_mode_sets_tds_8() {
let config = Config::new().strict_mode(true);
assert!(config.strict_mode);
assert_eq!(config.tds_version, TdsVersion::V8_0);
}
#[test]
fn test_connection_string_tds_version() {
// Test TDS 7.3
let config = Config::from_connection_string("Server=localhost;TDSVersion=7.3;").unwrap();
assert_eq!(config.tds_version, TdsVersion::V7_3A);
// Test TDS 7.3A explicitly
let config = Config::from_connection_string("Server=localhost;TDSVersion=7.3A;").unwrap();
assert_eq!(config.tds_version, TdsVersion::V7_3A);
// Test TDS 7.3B
let config = Config::from_connection_string("Server=localhost;TDSVersion=7.3B;").unwrap();
assert_eq!(config.tds_version, TdsVersion::V7_3B);
// Test TDS 7.4
let config = Config::from_connection_string("Server=localhost;TDSVersion=7.4;").unwrap();
assert_eq!(config.tds_version, TdsVersion::V7_4);
// Test TDS 8.0 enables strict mode
let config = Config::from_connection_string("Server=localhost;TDSVersion=8.0;").unwrap();
assert_eq!(config.tds_version, TdsVersion::V8_0);
assert!(config.strict_mode);
// Test alternative key names
let config =
Config::from_connection_string("Server=localhost;ProtocolVersion=7.3;").unwrap();
assert_eq!(config.tds_version, TdsVersion::V7_3A);
}
#[test]
fn test_connection_string_invalid_tds_version() {
let result = Config::from_connection_string("Server=localhost;TDSVersion=invalid;");
assert!(result.is_err());
let result = Config::from_connection_string("Server=localhost;TDSVersion=9.0;");
assert!(result.is_err());
}
#[test]
fn test_connection_string_no_tls() {
// no_tls should disable TLS entirely
let config = Config::from_connection_string("Server=legacy;Encrypt=no_tls;").unwrap();
assert!(config.no_tls);
assert!(!config.encrypt);
assert!(!config.strict_mode);
// Case insensitive
let config = Config::from_connection_string("Server=legacy;Encrypt=no_tls;").unwrap();
assert!(config.no_tls);
// Encrypt=true should disable no_tls
let config = Config::from_connection_string("Server=localhost;Encrypt=true;").unwrap();
assert!(!config.no_tls);
assert!(config.encrypt);
// Encrypt=strict should disable no_tls
let config = Config::from_connection_string("Server=localhost;Encrypt=strict;").unwrap();
assert!(!config.no_tls);
assert!(config.encrypt);
assert!(config.strict_mode);
// Encrypt=mandatory (Microsoft.Data.SqlClient v5+ alias for true)
let config = Config::from_connection_string("Server=localhost;Encrypt=mandatory;").unwrap();
assert!(config.encrypt);
assert!(!config.no_tls);
// Encrypt=optional (Microsoft.Data.SqlClient v5+ alias for false)
let config = Config::from_connection_string("Server=localhost;Encrypt=optional;").unwrap();
assert!(!config.encrypt);
assert!(!config.no_tls);
}
#[test]
fn test_no_tls_builder() {
// Builder method
let config = Config::new().no_tls(true);
assert!(config.no_tls);
assert!(!config.encrypt);
// Disable
let config = Config::new().no_tls(true).no_tls(false);
assert!(!config.no_tls);
}
#[test]
#[cfg(any(feature = "integrated-auth", feature = "sspi-auth"))]
fn test_connection_string_integrated_security() {
// "Integrated Security=true" should set Credentials::Integrated
let config =
Config::from_connection_string("Server=localhost;Integrated Security=true;").unwrap();
assert_eq!(
config.credentials.method_name(),
"Integrated Authentication"
);
// "yes" variant
let config =
Config::from_connection_string("Server=localhost;Integrated Security=yes;").unwrap();
assert_eq!(
config.credentials.method_name(),
"Integrated Authentication"
);
// "sspi" variant
let config =
Config::from_connection_string("Server=localhost;Integrated Security=sspi;").unwrap();
assert_eq!(
config.credentials.method_name(),
"Integrated Authentication"
);
// "1" variant
let config =
Config::from_connection_string("Server=localhost;Integrated Security=1;").unwrap();
assert_eq!(
config.credentials.method_name(),
"Integrated Authentication"
);
// Trusted_Connection synonym
let config =
Config::from_connection_string("Server=localhost;Trusted_Connection=true;").unwrap();
assert_eq!(
config.credentials.method_name(),
"Integrated Authentication"
);
}
#[test]
#[cfg(not(any(feature = "integrated-auth", feature = "sspi-auth")))]
fn test_connection_string_integrated_security_without_feature() {
// Should return an error when the feature is not enabled
let result = Config::from_connection_string("Server=localhost;Integrated Security=true;");
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(err.contains("integrated-auth"));
}
// =======================================================================
// ADO.NET conformance tests (quoted values, aliases, boolean validation)
// =======================================================================
#[test]
fn test_parse_conn_bool_all_values() {
assert!(parse_conn_bool("test", "true").unwrap());
assert!(parse_conn_bool("test", "True").unwrap());
assert!(parse_conn_bool("test", "TRUE").unwrap());
assert!(parse_conn_bool("test", "yes").unwrap());
assert!(parse_conn_bool("test", "Yes").unwrap());
assert!(parse_conn_bool("test", "1").unwrap());
assert!(!parse_conn_bool("test", "false").unwrap());
assert!(!parse_conn_bool("test", "False").unwrap());
assert!(!parse_conn_bool("test", "FALSE").unwrap());
assert!(!parse_conn_bool("test", "no").unwrap());
assert!(!parse_conn_bool("test", "No").unwrap());
assert!(!parse_conn_bool("test", "0").unwrap());
// Invalid values should error
assert!(parse_conn_bool("test", "banana").is_err());
assert!(parse_conn_bool("test", "tru").is_err());
assert!(parse_conn_bool("test", "").is_err());
}
#[test]
fn test_boolean_validation_trust_server_certificate() {
// Valid boolean → ok
let config =
Config::from_connection_string("Server=localhost;TrustServerCertificate=true;")
.unwrap();
assert!(config.trust_server_certificate);
let config =
Config::from_connection_string("Server=localhost;TrustServerCertificate=no;").unwrap();
assert!(!config.trust_server_certificate);
// Invalid boolean → error (previously silently set to false!)
let result =
Config::from_connection_string("Server=localhost;TrustServerCertificate=banana;");
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("invalid boolean"));
}
#[test]
fn test_boolean_validation_mars() {
let config = Config::from_connection_string("Server=localhost;MARS=true;").unwrap();
assert!(config.mars);
// Typo → error instead of silent false
let result = Config::from_connection_string("Server=localhost;MARS=tru;");
assert!(result.is_err());
}
#[test]
fn test_quoted_value_semicolon() {
// Password with semicolons — must be quoted per ADO.NET spec
let config = Config::from_connection_string(
r#"Server=localhost;User Id=sa;Password="my;complex;pass";"#,
)
.unwrap();
if let mssql_auth::Credentials::SqlServer { password, .. } = &config.credentials {
assert_eq!(password.as_ref(), "my;complex;pass");
} else {
unreachable!("expected SqlServer credentials");
}
}
#[test]
fn test_quoted_value_single_quotes() {
let config =
Config::from_connection_string("Server=localhost;User Id=sa;Password='my;pass';")
.unwrap();
if let mssql_auth::Credentials::SqlServer { password, .. } = &config.credentials {
assert_eq!(password.as_ref(), "my;pass");
} else {
unreachable!("expected SqlServer credentials");
}
}
#[test]
fn test_quoted_value_escaped_double_quotes() {
// Doubled quotes → single quote per ADO.NET spec
let config = Config::from_connection_string(
r#"Server=localhost;User Id=sa;Password="has ""quotes""";"#,
)
.unwrap();
if let mssql_auth::Credentials::SqlServer { password, .. } = &config.credentials {
assert_eq!(password.as_ref(), r#"has "quotes""#);
} else {
unreachable!("expected SqlServer credentials");
}
}
#[test]
fn test_quoted_value_escaped_single_quotes() {
let config =
Config::from_connection_string("Server=localhost;User Id=sa;Password='it''s complex';")
.unwrap();
if let mssql_auth::Credentials::SqlServer { password, .. } = &config.credentials {
assert_eq!(password.as_ref(), "it's complex");
} else {
unreachable!("expected SqlServer credentials");
}
}
#[test]
fn test_quoted_value_unterminated() {
let result = Config::from_connection_string(r#"Server=localhost;Password="unterminated;"#);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("unterminated"));
}
#[test]
fn test_tcp_prefix_stripped() {
// Azure Portal format: tcp:hostname,port
let config = Config::from_connection_string(
"Server=tcp:myserver.database.windows.net,1433;Database=mydb;",
)
.unwrap();
assert_eq!(config.host, "myserver.database.windows.net");
assert_eq!(config.port, 1433);
}
#[test]
fn test_tcp_prefix_mixed_case() {
// Protocol prefixes are case-insensitive per ADO.NET
let config = Config::from_connection_string("Server=Tcp:myhost,1433;").unwrap();
assert_eq!(config.host, "myhost");
let config = Config::from_connection_string("Server=TCP:myhost,1433;").unwrap();
assert_eq!(config.host, "myhost");
}
#[test]
fn test_tcp_prefix_with_instance() {
let config =
Config::from_connection_string("Server=tcp:myhost\\INST;Database=test;").unwrap();
assert_eq!(config.host, "myhost");
assert_eq!(config.instance, Some("INST".to_string()));
}
#[test]
fn test_np_prefix_rejected() {
let result =
Config::from_connection_string(r"Server=np:\\myhost\pipe\sql\query;Database=test;");
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("Named Pipes"));
// Case-insensitive rejection
let result =
Config::from_connection_string(r"Server=NP:\\myhost\pipe\sql\query;Database=test;");
assert!(result.is_err());
}
#[test]
fn test_lpc_prefix_rejected() {
let result = Config::from_connection_string("Server=lpc:myhost;Database=test;");
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("Shared Memory"));
}
#[test]
fn test_server_alias_addr() {
let config = Config::from_connection_string("Addr=myhost;").unwrap();
assert_eq!(config.host, "myhost");
}
#[test]
fn test_server_alias_address() {
let config = Config::from_connection_string("Address=myhost,1434;").unwrap();
assert_eq!(config.host, "myhost");
assert_eq!(config.port, 1434);
}
#[test]
fn test_server_alias_network_address() {
let config = Config::from_connection_string("Network Address=myhost;").unwrap();
assert_eq!(config.host, "myhost");
}
#[test]
fn test_timeout_alias() {
let config = Config::from_connection_string("Server=localhost;Timeout=30;").unwrap();
assert_eq!(config.connect_timeout, Duration::from_secs(30));
}
#[test]
fn test_application_intent_readonly() {
let config =
Config::from_connection_string("Server=localhost;ApplicationIntent=ReadOnly;").unwrap();
assert_eq!(config.application_intent, ApplicationIntent::ReadOnly);
}
#[test]
fn test_application_intent_readwrite() {
let config =
Config::from_connection_string("Server=localhost;Application Intent=ReadWrite;")
.unwrap();
assert_eq!(config.application_intent, ApplicationIntent::ReadWrite);
}
#[test]
fn test_application_intent_invalid() {
let result = Config::from_connection_string("Server=localhost;ApplicationIntent=banana;");
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("ApplicationIntent")
);
}
#[test]
fn test_workstation_id() {
let config =
Config::from_connection_string("Server=localhost;Workstation ID=MYPC;").unwrap();
assert_eq!(config.workstation_id, Some("MYPC".to_string()));
}
#[test]
fn test_wsid_alias() {
let config =
Config::from_connection_string("Server=localhost;WSID=MYWORKSTATION;").unwrap();
assert_eq!(config.workstation_id, Some("MYWORKSTATION".to_string()));
}
#[test]
fn test_language() {
let config =
Config::from_connection_string("Server=localhost;Language=us_english;").unwrap();
assert_eq!(config.language, Some("us_english".to_string()));
}
#[test]
fn test_current_language_alias() {
let config =
Config::from_connection_string("Server=localhost;Current Language=Deutsch;").unwrap();
assert_eq!(config.language, Some("Deutsch".to_string()));
}
#[test]
fn test_connect_retry_count() {
let config =
Config::from_connection_string("Server=localhost;ConnectRetryCount=5;").unwrap();
assert_eq!(config.retry.max_retries, 5);
}
#[test]
fn test_connect_retry_interval() {
let config =
Config::from_connection_string("Server=localhost;ConnectRetryInterval=15;").unwrap();
assert_eq!(config.retry.initial_backoff, Duration::from_secs(15));
}
#[test]
fn test_pool_keywords_accepted_without_error() {
// Pool keywords should be recognized (not error) but not affect Config
let result = Config::from_connection_string(
"Server=localhost;Max Pool Size=10;Min Pool Size=2;Pooling=true;",
);
assert!(result.is_ok());
}
#[test]
fn test_known_unsupported_keywords_accepted() {
// Known ADO.NET keywords we don't support should not error
let result = Config::from_connection_string(
"Server=localhost;Failover Partner=backup;Persist Security Info=false;",
);
assert!(result.is_ok());
}
#[test]
fn test_multi_subnet_failover_connection_string() {
let config =
Config::from_connection_string("Server=ag-listener;MultiSubnetFailover=true;").unwrap();
assert!(config.multi_subnet_failover);
// Space-separated variant
let config =
Config::from_connection_string("Server=ag-listener;Multi Subnet Failover=true;")
.unwrap();
assert!(config.multi_subnet_failover);
// Disabled
let config =
Config::from_connection_string("Server=ag-listener;MultiSubnetFailover=false;")
.unwrap();
assert!(!config.multi_subnet_failover);
// Default is false
let config = Config::from_connection_string("Server=localhost;").unwrap();
assert!(!config.multi_subnet_failover);
}
#[test]
fn test_multi_subnet_failover_builder() {
let config = Config::new().multi_subnet_failover(true);
assert!(config.multi_subnet_failover);
let config = Config::new().multi_subnet_failover(false);
assert!(!config.multi_subnet_failover);
}
#[test]
fn test_multi_subnet_failover_invalid_value() {
let result = Config::from_connection_string("Server=localhost;MultiSubnetFailover=banana;");
assert!(result.is_err());
}
#[test]
fn test_application_intent_builder() {
let config = Config::new().application_intent(ApplicationIntent::ReadOnly);
assert_eq!(config.application_intent, ApplicationIntent::ReadOnly);
}
#[test]
fn test_workstation_id_builder() {
let config = Config::new().workstation_id("MY-PC");
assert_eq!(config.workstation_id, Some("MY-PC".to_string()));
}
#[test]
fn test_language_builder() {
let config = Config::new().language("us_english");
assert_eq!(config.language, Some("us_english".to_string()));
}
#[test]
fn test_send_string_parameters_as_unicode_connection_string() {
let config =
Config::from_connection_string("Server=localhost;SendStringParametersAsUnicode=false;")
.unwrap();
assert!(!config.send_string_parameters_as_unicode);
// Space-separated variant
let config = Config::from_connection_string(
"Server=localhost;Send String Parameters As Unicode=false;",
)
.unwrap();
assert!(!config.send_string_parameters_as_unicode);
// Enabled explicitly
let config =
Config::from_connection_string("Server=localhost;SendStringParametersAsUnicode=true;")
.unwrap();
assert!(config.send_string_parameters_as_unicode);
// Default is true
let config = Config::from_connection_string("Server=localhost;").unwrap();
assert!(config.send_string_parameters_as_unicode);
}
#[test]
fn test_send_string_parameters_as_unicode_builder() {
let config = Config::new().send_string_parameters_as_unicode(false);
assert!(!config.send_string_parameters_as_unicode);
let config = Config::new().send_string_parameters_as_unicode(true);
assert!(config.send_string_parameters_as_unicode);
}
#[test]
fn test_send_string_parameters_as_unicode_invalid_value() {
let result = Config::from_connection_string(
"Server=localhost;SendStringParametersAsUnicode=banana;",
);
assert!(result.is_err());
}
#[test]
fn test_empty_values_become_none() {
// Per ADO.NET, empty values reset optional fields to default (None)
let config =
Config::from_connection_string("Server=localhost;Database=;Language=;").unwrap();
assert_eq!(config.database, None);
assert_eq!(config.language, None);
}
}