tiberius-ng 0.13.1

A TDS (Microsoft SQL Server) driver for Rust — actively-maintained community continuation of tiberius
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
mod ado_net;
mod jdbc;

use std::collections::HashMap;
use std::path::PathBuf;

use super::AuthMethod;
use crate::EncryptionLevel;
use ado_net::*;
use jdbc::*;

#[derive(Clone, Debug)]
/// The `Config` struct contains all configuration information
/// required for connecting to the database with a [`Client`]. It also provides
/// the server address when connecting to a `TcpStream` via the
/// [`get_addr`] method.
///
/// When using an [ADO.NET connection string], it can be
/// constructed using the [`from_ado_string`] function.
///
/// Alternatively, a [`ConfigBuilder`] can be used for an ergonomic,
/// chainable construction. Create one via [`builder`], call its
/// setter methods and finalize it with [`build`].
///
/// [`Client`]: struct.Client.html
/// [ADO.NET connection string]: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings
/// [`from_ado_string`]: struct.Config.html#method.from_ado_string
/// [`get_addr`]: struct.Config.html#method.get_addr
/// [`ConfigBuilder`]: struct.ConfigBuilder.html
/// [`builder`]: struct.Config.html#method.builder
/// [`build`]: struct.ConfigBuilder.html#method.build
pub struct Config {
    pub(crate) host: Option<String>,
    pub(crate) port: Option<u16>,
    pub(crate) database: Option<String>,
    pub(crate) instance_name: Option<String>,
    pub(crate) application_name: Option<String>,
    pub(crate) encryption: EncryptionLevel,
    pub(crate) trust: TrustConfig,
    pub(crate) auth: AuthMethod,
    pub(crate) readonly: bool,
    pub(crate) packet_size: Option<u32>,
    pub(crate) hostname_in_certificate: Option<String>,
    pub(crate) client_name: Option<String>,
    pub(crate) multi_subnet_failover: bool,
    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    pub(crate) client_cert: Option<ClientCertificate>,
}

#[derive(Clone, Debug)]
pub(crate) enum TrustConfig {
    #[allow(dead_code)]
    CaCertificateLocation(PathBuf),
    TrustAll,
    Default,
}

/// A client certificate and its private key, presented to the server during the
/// TLS handshake to authenticate the *client* (mutual TLS / TDS 8.0
/// `ENCRYPT_CLIENT_CERT`).
///
/// Construct one indirectly via [`Config::client_certificate`] (PEM/DER
/// certificate + private-key files) or [`Config::client_certificate_pkcs12`]
/// (a PKCS#12 / PFX bundle, `native-tls` and `vendored-openssl` only).
#[cfg(any(
    feature = "rustls",
    feature = "native-tls",
    feature = "vendored-openssl"
))]
#[derive(Clone, Debug)]
pub(crate) struct ClientCertificate {
    pub(crate) source: ClientCertSource,
}

#[cfg(any(
    feature = "rustls",
    feature = "native-tls",
    feature = "vendored-openssl"
))]
#[derive(Clone)]
pub(crate) enum ClientCertSource {
    /// A certificate file and a separate private-key file. Both may be PEM
    /// (`.pem`/`.crt` for the certificate, `.pem`/`.key` for the key) or DER
    /// (`.der`); the concrete format is detected from the file extension by the
    /// active TLS backend.
    CertAndKey { cert: PathBuf, key: PathBuf },
    /// A PKCS#12 / PFX bundle path together with its decryption password. Only
    /// supported by the `native-tls` and `vendored-openssl` backends.
    #[cfg(any(feature = "native-tls", feature = "vendored-openssl"))]
    Pkcs12 {
        path: PathBuf,
        password: zeroize::Zeroizing<String>,
    },
}

// Manual `Debug` so the PKCS#12 password is never printed.
#[cfg(any(
    feature = "rustls",
    feature = "native-tls",
    feature = "vendored-openssl"
))]
impl std::fmt::Debug for ClientCertSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ClientCertSource::CertAndKey { cert, key } => f
                .debug_struct("CertAndKey")
                .field("cert", cert)
                .field("key", key)
                .finish(),
            #[cfg(any(feature = "native-tls", feature = "vendored-openssl"))]
            ClientCertSource::Pkcs12 { path, .. } => f
                .debug_struct("Pkcs12")
                .field("path", path)
                .field("password", &"<redacted>")
                .finish(),
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            host: None,
            port: None,
            database: None,
            instance_name: None,
            application_name: None,
            #[cfg(any(
                feature = "rustls",
                feature = "native-tls",
                feature = "vendored-openssl"
            ))]
            encryption: EncryptionLevel::Required,
            #[cfg(not(any(
                feature = "rustls",
                feature = "native-tls",
                feature = "vendored-openssl"
            )))]
            encryption: EncryptionLevel::NotSupported,
            trust: TrustConfig::Default,
            auth: AuthMethod::None,
            readonly: false,
            packet_size: None,
            hostname_in_certificate: None,
            client_name: None,
            multi_subnet_failover: false,
            #[cfg(any(
                feature = "rustls",
                feature = "native-tls",
                feature = "vendored-openssl"
            ))]
            client_cert: None,
        }
    }
}

impl Config {
    /// Create a new `Config` with the default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new [`ConfigBuilder`] initialized with the default settings.
    ///
    /// This provides an ergonomic, chainable alternative to constructing a
    /// [`Config`] via its individual setter methods.
    ///
    /// # Example
    ///
    /// ```
    /// # use tiberius::{Config, AuthMethod};
    /// let config = Config::builder()
    ///     .host("localhost")
    ///     .port(1433)
    ///     .database("master")
    ///     .authentication(AuthMethod::sql_server("SA", "<password>"))
    ///     .build();
    ///
    /// assert_eq!("localhost:1433", config.get_addr());
    /// ```
    ///
    /// [`ConfigBuilder`]: struct.ConfigBuilder.html
    /// [`Config`]: struct.Config.html
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder {
            inner: Self::default(),
        }
    }

    /// A host or ip address to connect to.
    ///
    /// - Defaults to `localhost`.
    pub fn host(&mut self, host: impl ToString) {
        self.host = Some(host.to_string());
    }

    /// The server port.
    ///
    /// - Defaults to `1433`.
    pub fn port(&mut self, port: u16) {
        self.port = Some(port);
    }

    /// The database to connect to.
    ///
    /// - Defaults to `master`.
    pub fn database(&mut self, database: impl ToString) {
        self.database = Some(database.to_string())
    }

    /// The instance name as defined in the SQL Browser. Only available on
    /// Windows platforms.
    ///
    /// If specified, the port is replaced with the value returned from the
    /// browser.
    ///
    /// - Defaults to no name specified.
    pub fn instance_name(&mut self, name: impl ToString) {
        self.instance_name = Some(name.to_string());
    }

    /// Sets the application name to the connection, queryable with the
    /// `APP_NAME()` command.
    ///
    /// - Defaults to no name specified.
    pub fn application_name(&mut self, name: impl ToString) {
        self.application_name = Some(name.to_string());
    }

    /// Sets the TDS packet size for the connection.
    ///
    /// Larger packet sizes can improve bulk insert performance by reducing
    /// the number of network round-trips. Valid values are 512 to 32767.
    /// The server may negotiate a different size.
    ///
    /// - Defaults to 4096 bytes.
    pub fn packet_size(&mut self, size: u32) {
        self.packet_size = Some(size);
    }

    /// Gets the configured packet size, if set.
    pub fn get_packet_size(&self) -> Option<u32> {
        self.packet_size
    }

    /// Set the preferred encryption level.
    ///
    /// - With `tls` feature, defaults to `Required`.
    /// - Without `tls` feature, defaults to `NotSupported`.
    pub fn encryption(&mut self, encryption: EncryptionLevel) {
        self.encryption = encryption;
    }

    /// If set, the server certificate will not be validated and it is accepted
    /// as-is.
    ///
    /// On production setting, the certificate should be added to the local key
    /// storage (or use `trust_cert_ca` instead), using this setting is potentially dangerous.
    ///
    /// # Panics
    /// Will panic in case `trust_cert_ca` was called before.
    ///
    /// - Defaults to `default`, meaning server certificate is validated against system-truststore.
    pub fn trust_cert(&mut self) {
        if let TrustConfig::CaCertificateLocation(_) = &self.trust {
            panic!("'trust_cert' and 'trust_cert_ca' are mutual exclusive! Only use one.")
        }
        self.trust = TrustConfig::TrustAll;
    }

    /// If set, the server certificate will be validated against the given CA certificate in
    /// in addition to the system-truststore.
    /// Useful when using self-signed certificates on the server without having to disable the
    /// trust-chain.
    ///
    /// # Panics
    /// Will panic in case `trust_cert` was called before.
    ///
    /// - Defaults to validating the server certificate is validated against system's certificate storage.
    pub fn trust_cert_ca(&mut self, path: impl ToString) {
        if let TrustConfig::TrustAll = &self.trust {
            panic!("'trust_cert' and 'trust_cert_ca' are mutual exclusive! Only use one.")
        } else {
            self.trust = TrustConfig::CaCertificateLocation(PathBuf::from(path.to_string()))
        }
    }

    /// Sets the hostname that the server certificate is validated against,
    /// instead of the value given to [`host`].
    ///
    /// This is useful when connecting through an IP address, a tunnel, or a
    /// load balancer whose certificate carries a different subject/SAN than the
    /// address used to reach it (see issue #340).
    ///
    /// - Defaults to the value of [`host`].
    ///
    /// [`host`]: Config::host
    pub fn hostname_in_certificate(&mut self, hostname: impl ToString) {
        self.hostname_in_certificate = Some(hostname.to_string());
    }

    /// Sets the client / workstation name reported to the server in the login
    /// record (queryable with `HOST_NAME()`).
    ///
    /// - Defaults to the local workstation id (the machine hostname).
    pub fn client_name(&mut self, name: impl ToString) {
        self.client_name = Some(name.to_string());
    }

    /// Sets the authentication method.
    ///
    /// - Defaults to `None`.
    pub fn authentication(&mut self, auth: AuthMethod) {
        self.auth = auth;
    }

    /// Sets ApplicationIntent readonly.
    ///
    /// - Defaults to `false`.
    pub fn readonly(&mut self, readnoly: bool) {
        self.readonly = readnoly;
    }

    /// Enable multi-subnet failover.
    ///
    /// When enabled and the server host name resolves to more than one IP
    /// address (for example, an Always On availability group listener spread
    /// across subnets), connections are attempted to all resolved addresses in
    /// parallel and the first one to succeed is used. This mirrors the ADO.NET
    /// `MultiSubnetFailover` connection-string keyword.
    ///
    /// - Defaults to `false`.
    pub fn multi_subnet_failover(&mut self, multi_subnet_failover: bool) {
        self.multi_subnet_failover = multi_subnet_failover;
    }

    /// Returns whether multi-subnet failover is enabled.
    pub fn get_multi_subnet_failover(&self) -> bool {
        self.multi_subnet_failover
    }

    /// Supplies a client certificate and private key used to authenticate the
    /// client to the server during the TLS handshake (mutual TLS). This is
    /// required for TDS 8.0 "strict" connections that use client-certificate
    /// authentication (`ENCRYPT_CLIENT_CERT`), and may also be used with the
    /// classic (pre-8.0) TLS handshake when the server requests a client
    /// certificate.
    ///
    /// Both arguments are paths to files:
    ///
    /// - `cert`: the client certificate, PEM (`.pem`/`.crt`) or DER (`.der`).
    /// - `key`: the matching private key, PEM (`.pem`/`.key`) or DER (`.der`,
    ///   PKCS#8).
    ///
    /// Backend support:
    ///
    /// - `rustls`: PEM and DER certificate/key files.
    /// - `native-tls`: PEM certificate + PEM PKCS#8 key only (DER files are
    ///   rejected at connect time; use [`client_certificate_pkcs12`] for a
    ///   bundled DER identity).
    /// - `vendored-openssl` (opentls): does not support separate certificate/key
    ///   files; use [`client_certificate_pkcs12`] instead.
    ///
    /// - Defaults to no client certificate.
    ///
    /// [`client_certificate_pkcs12`]: Config::client_certificate_pkcs12
    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    #[cfg_attr(
        docsrs,
        doc(cfg(any(
            feature = "rustls",
            feature = "native-tls",
            feature = "vendored-openssl"
        )))
    )]
    pub fn client_certificate(&mut self, cert: impl Into<PathBuf>, key: impl Into<PathBuf>) {
        self.client_cert = Some(ClientCertificate {
            source: ClientCertSource::CertAndKey {
                cert: cert.into(),
                key: key.into(),
            },
        });
    }

    /// Supplies a client identity from a PKCS#12 / PFX bundle (certificate,
    /// private key and any chain, encrypted with `password`) used to
    /// authenticate the client to the server during the TLS handshake (mutual
    /// TLS).
    ///
    /// Only supported by the `native-tls` and `vendored-openssl` backends; the
    /// `rustls` backend rejects PKCS#12 identities at connect time (supply
    /// separate PEM/DER files via [`client_certificate`] instead).
    ///
    /// - Defaults to no client certificate.
    ///
    /// [`client_certificate`]: Config::client_certificate
    #[cfg(any(feature = "native-tls", feature = "vendored-openssl"))]
    #[cfg_attr(
        docsrs,
        doc(cfg(any(feature = "native-tls", feature = "vendored-openssl")))
    )]
    pub fn client_certificate_pkcs12(
        &mut self,
        path: impl Into<PathBuf>,
        password: impl Into<String>,
    ) {
        self.client_cert = Some(ClientCertificate {
            source: ClientCertSource::Pkcs12 {
                path: path.into(),
                password: zeroize::Zeroizing::new(password.into()),
            },
        });
    }

    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    pub(crate) fn get_client_certificate(&self) -> Option<&ClientCertificate> {
        self.client_cert.as_ref()
    }

    pub(crate) fn get_host(&self) -> &str {
        self.host
            .as_deref()
            .filter(|v| v != &".")
            .unwrap_or("localhost")
    }

    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    pub(crate) fn get_hostname_in_certificate(&self) -> &str {
        self.hostname_in_certificate
            .as_deref()
            .unwrap_or_else(|| self.get_host())
    }

    pub(crate) fn get_port(&self) -> u16 {
        match (self.port, self.instance_name.as_ref()) {
            // A user-defined port, we must use that.
            (Some(port), _) => port,
            // If using a named instance, we'll give the default port of SQL
            // Browser.
            (None, Some(_)) => 1434,
            // Otherwise the defaulting to the default SQL Server port.
            (None, None) => 1433,
        }
    }

    /// Get the host address including port
    pub fn get_addr(&self) -> String {
        format!("{}:{}", self.get_host(), self.get_port())
    }

    /// Creates a new `Config` from an [ADO.NET connection string].
    ///
    /// # Supported parameters
    ///
    /// All parameter keys are handled case-insensitive.
    ///
    /// |Parameter|Allowed values|Description|
    /// |--------|--------|--------|
    /// |`server`|`<string>`|The name or network address of the instance of SQL Server to which to connect. The port number can be specified after the server name. The correct form of this parameter is either `tcp:host,port` or `tcp:host\\instance`|
    /// |`IntegratedSecurity`|`true`,`false`,`yes`,`no`|Toggle between Windows/Kerberos authentication and SQL authentication.|
    /// |`uid`,`username`,`user`,`user id`|`<string>`|The SQL Server login account.|
    /// |`password`,`pwd`|`<string>`|The password for the SQL Server account logging on.|
    /// |`database`|`<string>`|The name of the database.|
    /// |`TrustServerCertificate`|`true`,`false`,`yes`,`no`|Specifies whether the driver trusts the server certificate when connecting using TLS. Cannot be used toghether with `TrustServerCertificateCA`|
    /// |`TrustServerCertificateCA`|`<path>`|Path to a `pem`, `crt` or `der` certificate file. Cannot be used together with `TrustServerCertificate`|
    /// |`encrypt`|`strict`,`true`,`false`,`yes`,`no`,`DANGER_PLAINTEXT`|Specifies whether the driver uses TLS to encrypt communication. `strict` (TDS 8.0) requires the `tds80` feature.|
    /// |`Application Name`, `ApplicationName`|`<string>`|Sets the application name for the connection.|
    /// |`HostNameInCertificate`, `HostName In Certificate`|`<string>`|The hostname the server certificate is validated against. Defaults to `server`.|
    /// |`WorkstationID`, `Workstation ID`|`<string>`|The client / workstation name reported to the server.|
    /// |`MultiSubnetFailover`|`true`,`false`,`yes`,`no`|When enabled, connections are attempted in parallel to all IP addresses the server resolves to, and the first to succeed is used.|
    ///
    /// [ADO.NET connection string]: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings
    pub fn from_ado_string(s: &str) -> crate::Result<Self> {
        let ado: AdoNetConfig = s.parse()?;
        Self::from_config_string(ado)
    }

    /// Creates a new `Config` from a [JDBC connection string].
    ///
    /// See [`from_ado_string`] method for supported parameters.
    ///
    /// [JDBC connection string]: https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15
    /// [`from_ado_string`]: #method.from_ado_string
    pub fn from_jdbc_string(s: &str) -> crate::Result<Self> {
        let jdbc: JdbcConfig = s.parse()?;
        Self::from_config_string(jdbc)
    }

    fn from_config_string(s: impl ConfigString) -> crate::Result<Self> {
        let mut builder = Self::new();

        let server = s.server()?;

        if let Some(host) = server.host {
            builder.host(host);
        }

        if let Some(port) = server.port {
            builder.port(port);
        }

        if let Some(instance) = server.instance {
            builder.instance_name(instance);
        }

        builder.authentication(s.authentication()?);

        if let Some(database) = s.database() {
            builder.database(database);
        }

        if let Some(name) = s.application_name() {
            builder.application_name(name);
        }

        if s.trust_cert()? {
            builder.trust_cert();
        }

        if let Some(ca) = s.trust_cert_ca() {
            builder.trust_cert_ca(ca);
        }

        if let Some(hostname_in_cert) = s.hostname_in_certificate() {
            builder.hostname_in_certificate(hostname_in_cert);
        }

        builder.encryption(s.encrypt()?);

        builder.readonly(s.readonly());

        if let Some(client_name) = s.client_name() {
            builder.client_name(client_name);
        }
        builder.multi_subnet_failover(s.multi_subnet_failover()?);

        Ok(builder)
    }
}

/// A builder for [`Config`], providing an ergonomic, chainable way to
/// construct a connection configuration.
///
/// Create a builder with [`Config::builder`], set the desired options by
/// calling its methods (each returns the builder to allow chaining) and
/// finalize it with [`build`].
///
/// # Example
///
/// ```
/// # use tiberius::{Config, AuthMethod, EncryptionLevel};
/// let config = Config::builder()
///     .host("localhost")
///     .port(1433)
///     .database("master")
///     .encryption(EncryptionLevel::NotSupported)
///     .authentication(AuthMethod::sql_server("SA", "<password>"))
///     .build();
/// ```
///
/// [`Config`]: struct.Config.html
/// [`Config::builder`]: struct.Config.html#method.builder
/// [`build`]: struct.ConfigBuilder.html#method.build
#[derive(Clone, Debug)]
pub struct ConfigBuilder {
    inner: Config,
}

impl ConfigBuilder {
    /// A host or ip address to connect to.
    ///
    /// - Defaults to `localhost`.
    pub fn host(mut self, host: impl ToString) -> Self {
        self.inner.host = Some(host.to_string());
        self
    }

    /// The server port.
    ///
    /// - Defaults to `1433`.
    pub fn port(mut self, port: u16) -> Self {
        self.inner.port = Some(port);
        self
    }

    /// The database to connect to.
    ///
    /// - Defaults to `master`.
    pub fn database(mut self, database: impl ToString) -> Self {
        self.inner.database = Some(database.to_string());
        self
    }

    /// The instance name as defined in the SQL Browser. Only available on
    /// Windows platforms.
    ///
    /// If specified, the port is replaced with the value returned from the
    /// browser.
    ///
    /// - Defaults to no name specified.
    pub fn instance_name(mut self, name: impl ToString) -> Self {
        self.inner.instance_name = Some(name.to_string());
        self
    }

    /// Sets the application name to the connection, queryable with the
    /// `APP_NAME()` command.
    ///
    /// - Defaults to no name specified.
    pub fn application_name(mut self, name: impl ToString) -> Self {
        self.inner.application_name = Some(name.to_string());
        self
    }

    /// Set the preferred encryption level.
    ///
    /// - With `tls` feature, defaults to `Required`.
    /// - Without `tls` feature, defaults to `NotSupported`.
    pub fn encryption(mut self, encryption: EncryptionLevel) -> Self {
        self.inner.encryption = encryption;
        self
    }

    /// If set, the server certificate will not be validated and it is accepted
    /// as-is.
    ///
    /// On production setting, the certificate should be added to the local key
    /// storage (or use `trust_cert_ca` instead), using this setting is potentially dangerous.
    ///
    /// # Panics
    /// Will panic in case `trust_cert_ca` was called before.
    ///
    /// - Defaults to `default`, meaning server certificate is validated against system-truststore.
    pub fn trust_cert(mut self) -> Self {
        if let TrustConfig::CaCertificateLocation(_) = &self.inner.trust {
            panic!("'trust_cert' and 'trust_cert_ca' are mutual exclusive! Only use one.")
        }
        self.inner.trust = TrustConfig::TrustAll;
        self
    }

    /// If set, the server certificate will be validated against the given CA certificate in
    /// in addition to the system-truststore.
    /// Useful when using self-signed certificates on the server without having to disable the
    /// trust-chain.
    ///
    /// # Panics
    /// Will panic in case `trust_cert` was called before.
    ///
    /// - Defaults to validating the server certificate is validated against system's certificate storage.
    pub fn trust_cert_ca(mut self, path: impl ToString) -> Self {
        if let TrustConfig::TrustAll = &self.inner.trust {
            panic!("'trust_cert' and 'trust_cert_ca' are mutual exclusive! Only use one.")
        } else {
            self.inner.trust = TrustConfig::CaCertificateLocation(PathBuf::from(path.to_string()))
        }
        self
    }

    /// Sets the authentication method.
    ///
    /// - Defaults to `None`.
    pub fn authentication(mut self, auth: AuthMethod) -> Self {
        self.inner.auth = auth;
        self
    }

    /// Sets ApplicationIntent readonly.
    ///
    /// - Defaults to `false`.
    pub fn readonly(mut self, readonly: bool) -> Self {
        self.inner.readonly = readonly;
        self
    }

    /// Supplies a client certificate and private key for mutual TLS.
    ///
    /// See [`Config::client_certificate`] for details and backend support.
    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    #[cfg_attr(
        docsrs,
        doc(cfg(any(
            feature = "rustls",
            feature = "native-tls",
            feature = "vendored-openssl"
        )))
    )]
    pub fn client_certificate(mut self, cert: impl Into<PathBuf>, key: impl Into<PathBuf>) -> Self {
        self.inner.client_certificate(cert, key);
        self
    }

    /// Supplies a client identity from a PKCS#12 / PFX bundle for mutual TLS.
    ///
    /// See [`Config::client_certificate_pkcs12`] for details and backend
    /// support.
    #[cfg(any(feature = "native-tls", feature = "vendored-openssl"))]
    #[cfg_attr(
        docsrs,
        doc(cfg(any(feature = "native-tls", feature = "vendored-openssl")))
    )]
    pub fn client_certificate_pkcs12(
        mut self,
        path: impl Into<PathBuf>,
        password: impl Into<String>,
    ) -> Self {
        self.inner.client_certificate_pkcs12(path, password);
        self
    }

    /// Produces the finalized [`Config`] from this builder.
    ///
    /// [`Config`]: struct.Config.html
    pub fn build(self) -> Config {
        self.inner
    }
}

impl From<Config> for ConfigBuilder {
    fn from(config: Config) -> Self {
        ConfigBuilder { inner: config }
    }
}

impl From<ConfigBuilder> for Config {
    fn from(builder: ConfigBuilder) -> Self {
        builder.inner
    }
}

pub(crate) struct ServerDefinition {
    host: Option<String>,
    port: Option<u16>,
    instance: Option<String>,
}

pub(crate) trait ConfigString {
    fn dict(&self) -> &HashMap<String, String>;

    fn server(&self) -> crate::Result<ServerDefinition>;

    fn authentication(&self) -> crate::Result<AuthMethod> {
        let user = self
            .dict()
            .get("uid")
            .or_else(|| self.dict().get("username"))
            .or_else(|| self.dict().get("user"))
            .or_else(|| self.dict().get("user id"))
            .map(|s| s.as_str());

        let pw = self
            .dict()
            .get("password")
            .or_else(|| self.dict().get("pwd"))
            .map(|s| s.as_str());

        match self
            .dict()
            .get("integratedsecurity")
            .or_else(|| self.dict().get("integrated security"))
        {
            #[cfg(all(windows, feature = "winauth"))]
            Some(val) if val.to_lowercase() == "sspi" || Self::parse_bool(val)? => match (user, pw)
            {
                (None, None) => Ok(AuthMethod::Integrated),
                _ => Ok(AuthMethod::windows(user.unwrap_or(""), pw.unwrap_or(""))),
            },
            // On Unix with `sspi-rs`, `IntegratedSecurity=SSPI` (or a truthy
            // value) uses NTLM when a username/password is supplied, and falls
            // back to Kerberos (`Integrated`) only if `integrated-auth-gssapi`
            // is also enabled and no credentials are given.
            #[cfg(all(unix, feature = "sspi-rs"))]
            Some(val) if val.to_lowercase() == "sspi" || Self::parse_bool(val)? => {
                match (user, pw) {
                    (Some(user), Some(pw)) => Ok(AuthMethod::windows(user, pw)),
                    #[cfg(feature = "integrated-auth-gssapi")]
                    (None, None) => Ok(AuthMethod::Integrated),
                    _ => Ok(AuthMethod::windows(user.unwrap_or(""), pw.unwrap_or(""))),
                }
            }
            #[cfg(all(
                feature = "integrated-auth-gssapi",
                not(all(unix, feature = "sspi-rs"))
            ))]
            Some(val) if val.to_lowercase() == "sspi" || Self::parse_bool(val)? => {
                Ok(AuthMethod::Integrated)
            }
            _ => Ok(AuthMethod::sql_server(user.unwrap_or(""), pw.unwrap_or(""))),
        }
    }

    fn database(&self) -> Option<String> {
        self.dict()
            .get("database")
            .or_else(|| self.dict().get("initial catalog"))
            .or_else(|| self.dict().get("databasename"))
            .map(|db| db.to_string())
    }

    fn application_name(&self) -> Option<String> {
        self.dict()
            .get("application name")
            .or_else(|| self.dict().get("applicationname"))
            .map(|name| name.to_string())
    }

    fn trust_cert(&self) -> crate::Result<bool> {
        self.dict()
            .get("trustservercertificate")
            .map(Self::parse_bool)
            .unwrap_or(Ok(false))
    }

    fn trust_cert_ca(&self) -> Option<String> {
        self.dict()
            .get("trustservercertificateca")
            .map(|ca| ca.to_string())
    }

    fn hostname_in_certificate(&self) -> Option<String> {
        self.dict()
            .get("hostnameincertificate")
            .or_else(|| self.dict().get("hostname in certificate"))
            .map(|host| host.to_string())
    }

    fn client_name(&self) -> Option<String> {
        self.dict()
            .get("workstationid")
            .or_else(|| self.dict().get("workstation id"))
            .map(|name| name.to_string())
    }

    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    fn encrypt(&self) -> crate::Result<EncryptionLevel> {
        self.dict()
            .get("encrypt")
            .map(|val| match Self::parse_bool(val) {
                Ok(true) => Ok(EncryptionLevel::Required),
                Ok(false) => Ok(EncryptionLevel::Off),
                Err(_) if val == "DANGER_PLAINTEXT" => Ok(EncryptionLevel::NotSupported),
                Err(_) if val.eq_ignore_ascii_case("strict") && cfg!(feature = "tds80") => {
                    Ok(EncryptionLevel::Strict)
                }
                Err(_) if val.eq_ignore_ascii_case("strict") => Err(crate::Error::Conversion(
                    "encrypt=strict requires the crate's `tds80` feature to be enabled".into(),
                )),
                Err(e) => Err(e),
            })
            // When the `encrypt` keyword is omitted, default to requiring
            // encryption — matching `Config::default()` and modern ADO.NET
            // (`Encrypt=Mandatory`). Callers who want an unencrypted connection
            // must opt out explicitly with `encrypt=false` (or
            // `encrypt=DANGER_PLAINTEXT`).
            .unwrap_or(Ok(EncryptionLevel::Required))
    }

    #[cfg(not(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    )))]
    fn encrypt(&self) -> crate::Result<EncryptionLevel> {
        Ok(EncryptionLevel::NotSupported)
    }

    fn parse_bool<T: AsRef<str>>(v: T) -> crate::Result<bool> {
        match v.as_ref().trim().to_lowercase().as_str() {
            "true" | "yes" => Ok(true),
            "false" | "no" => Ok(false),
            _ => Err(crate::Error::Conversion(
                "Connection string: Not a valid boolean".into(),
            )),
        }
    }

    fn readonly(&self) -> bool {
        self.dict()
            .get("applicationintent")
            .filter(|val| val.trim().eq_ignore_ascii_case("ReadOnly"))
            .is_some()
    }

    fn multi_subnet_failover(&self) -> crate::Result<bool> {
        self.dict()
            .get("multisubnetfailover")
            .map(Self::parse_bool)
            .unwrap_or(Ok(false))
    }
}

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

    #[test]
    fn config_builder_constructs_config() {
        let config = Config::builder()
            .host("db.example.com")
            .port(4433)
            .database("northwind")
            .application_name("my-app")
            .authentication(AuthMethod::sql_server("SA", "secret"))
            .readonly(true)
            .build();

        assert_eq!("db.example.com", config.get_host());
        assert_eq!(4433, config.get_port());
        assert_eq!("db.example.com:4433", config.get_addr());
        assert_eq!(Some("northwind"), config.database.as_deref());
        assert_eq!(Some("my-app"), config.application_name.as_deref());
        assert!(config.readonly);
        assert!(matches!(config.auth, AuthMethod::SqlServer(_)));
        assert!(matches!(config.trust, TrustConfig::Default));
    }

    #[test]
    fn config_builder_roundtrips_via_from() {
        let config = Config::builder().host("localhost").port(1433).build();
        let builder: ConfigBuilder = config.into();
        let config = builder.database("master").build();

        assert_eq!("localhost:1433", config.get_addr());
        assert_eq!(Some("master"), config.database.as_deref());
    }

    #[test]
    fn config_from_builder_carries_builder_settings() {
        // `From<ConfigBuilder>` must return the built inner config, not a default.
        let config: Config = Config::builder().host("db.internal").port(2020).into();
        assert_eq!("db.internal", config.get_host());
        assert_eq!(2020, config.get_port());
    }

    #[test]
    fn get_packet_size_reflects_the_set_value() {
        let mut config = Config::new();
        assert_eq!(config.get_packet_size(), None);
        config.packet_size(8192);
        assert_eq!(config.get_packet_size(), Some(8192));
    }

    #[test]
    fn from_jdbc_string_parses_host_and_port() {
        let config =
            Config::from_jdbc_string("jdbc:sqlserver://db.example.com:2345").expect("valid jdbc");
        assert_eq!("db.example.com", config.get_host());
        assert_eq!(2345, config.get_port());
    }

    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    #[test]
    fn get_hostname_in_certificate_falls_back_to_host() {
        let mut config = Config::new();
        config.host("real.host");
        // Unset: falls back to the connection host.
        assert_eq!(config.get_hostname_in_certificate(), "real.host");
        // Set: returns the explicit certificate hostname.
        config.hostname_in_certificate("cert.host");
        assert_eq!(config.get_hostname_in_certificate(), "cert.host");
    }

    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    #[test]
    fn client_certificate_sets_cert_and_key_source() {
        let mut config = Config::new();
        assert!(config.get_client_certificate().is_none());

        config.client_certificate("/tmp/client.pem", "/tmp/client.key");

        let cert = config
            .get_client_certificate()
            .expect("client certificate should be set");
        match &cert.source {
            ClientCertSource::CertAndKey { cert, key } => {
                assert_eq!(cert, &PathBuf::from("/tmp/client.pem"));
                assert_eq!(key, &PathBuf::from("/tmp/client.key"));
            }
            #[allow(unreachable_patterns)]
            other => panic!("expected CertAndKey source, got {other:?}"),
        }
    }

    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    #[test]
    fn config_builder_sets_client_certificate() {
        let config = Config::builder()
            .host("localhost")
            .client_certificate("cert.der", "key.der")
            .build();

        match &config
            .get_client_certificate()
            .expect("client certificate should be set")
            .source
        {
            ClientCertSource::CertAndKey { cert, key } => {
                assert_eq!(cert, &PathBuf::from("cert.der"));
                assert_eq!(key, &PathBuf::from("key.der"));
            }
            #[allow(unreachable_patterns)]
            other => panic!("expected CertAndKey source, got {other:?}"),
        }
    }

    #[cfg(any(feature = "native-tls", feature = "vendored-openssl"))]
    #[test]
    fn client_certificate_pkcs12_sets_bundle_source() {
        let mut config = Config::new();
        config.client_certificate_pkcs12("/tmp/identity.pfx", "s3cr3t");

        match &config
            .get_client_certificate()
            .expect("client certificate should be set")
            .source
        {
            ClientCertSource::Pkcs12 { path, password } => {
                assert_eq!(path, &PathBuf::from("/tmp/identity.pfx"));
                assert_eq!(password.as_str(), "s3cr3t");
            }
            other => panic!("expected Pkcs12 source, got {other:?}"),
        }
    }

    #[cfg(any(feature = "native-tls", feature = "vendored-openssl"))]
    #[test]
    fn client_certificate_debug_redacts_pkcs12_password() {
        let mut config = Config::new();
        config.client_certificate_pkcs12("/tmp/identity.pfx", "topsecret");

        let dbg = format!("{:?}", config.get_client_certificate().unwrap());
        assert!(dbg.contains("<redacted>"));
        assert!(!dbg.contains("topsecret"));
    }

    #[cfg(all(unix, feature = "sspi-rs"))]
    #[test]
    fn ado_integrated_security_sspi_with_credentials_uses_windows_ntlm() {
        let config = Config::from_ado_string(
            "server=tcp:localhost,1433;IntegratedSecurity=SSPI;uid=DOMAIN\\user;pwd=secret",
        )
        .unwrap();

        match config.auth {
            AuthMethod::Windows(auth) => {
                assert_eq!("user", auth.user);
                assert_eq!(Some("DOMAIN"), auth.domain.as_deref());
            }
            other => panic!("expected Windows NTLM auth, got {other:?}"),
        }
    }

    #[test]
    fn config_direct_setters_populate_fields() {
        let mut config = Config::new();
        config.database("northwind");
        config.instance_name("SQLEXPRESS");
        config.client_name("workstation-7");

        assert_eq!(Some("northwind"), config.database.as_deref());
        assert_eq!(Some("SQLEXPRESS"), config.instance_name.as_deref());
        assert_eq!(Some("workstation-7"), config.client_name.as_deref());
    }

    #[test]
    fn get_port_defaults_without_port_or_instance() {
        // No explicit port and no instance -> default SQL Server port.
        let config = Config::new();
        assert_eq!(1433, config.get_port());
    }

    #[test]
    fn get_port_uses_sql_browser_port_for_named_instance() {
        // A named instance without an explicit port -> SQL Browser port.
        let mut config = Config::new();
        config.instance_name("SQLEXPRESS");
        assert_eq!(1434, config.get_port());
    }

    #[test]
    #[should_panic(expected = "mutual exclusive")]
    fn trust_cert_after_trust_cert_ca_panics() {
        let mut config = Config::new();
        config.trust_cert_ca("/tmp/ca.crt");
        config.trust_cert();
    }

    #[test]
    #[should_panic(expected = "mutual exclusive")]
    fn trust_cert_ca_after_trust_cert_panics() {
        let mut config = Config::new();
        config.trust_cert();
        config.trust_cert_ca("/tmp/ca.crt");
    }

    #[test]
    fn trust_cert_ca_sets_ca_location() {
        let mut config = Config::new();
        config.trust_cert_ca("/tmp/ca.crt");
        assert!(matches!(
            config.trust,
            TrustConfig::CaCertificateLocation(_)
        ));
    }

    #[test]
    fn config_builder_covers_all_setters() {
        let config = Config::builder()
            .host("localhost")
            .instance_name("SQLEXPRESS")
            .encryption(EncryptionLevel::Off)
            .trust_cert_ca("/tmp/ca.crt")
            .build();

        assert_eq!(Some("SQLEXPRESS"), config.instance_name.as_deref());
        assert!(matches!(config.encryption, EncryptionLevel::Off));
        assert!(matches!(
            config.trust,
            TrustConfig::CaCertificateLocation(_)
        ));
    }

    #[test]
    fn config_builder_trust_cert_sets_trust_all() {
        let config = Config::builder().trust_cert().build();
        assert!(matches!(config.trust, TrustConfig::TrustAll));
    }

    #[test]
    #[should_panic(expected = "mutual exclusive")]
    fn config_builder_trust_cert_after_ca_panics() {
        Config::builder().trust_cert_ca("/tmp/ca.crt").trust_cert();
    }

    #[test]
    #[should_panic(expected = "mutual exclusive")]
    fn config_builder_trust_cert_ca_after_trust_cert_panics() {
        Config::builder().trust_cert().trust_cert_ca("/tmp/ca.crt");
    }

    #[test]
    fn from_ado_string_populates_optional_fields() {
        let config = Config::from_ado_string(
            "server=tcp:my-server.com\\SQLEXPRESS;database=northwind;\
             HostNameInCertificate=cert.host;WorkstationID=ws-1",
        )
        .expect("valid ado string");

        assert_eq!("my-server.com", config.get_host());
        assert_eq!(Some("SQLEXPRESS"), config.instance_name.as_deref());
        assert_eq!(Some("northwind"), config.database.as_deref());
        assert_eq!(Some("cert.host"), config.hostname_in_certificate.as_deref());
        assert_eq!(Some("ws-1"), config.client_name.as_deref());
    }

    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    #[test]
    fn client_cert_source_debug_formats_cert_and_key() {
        let mut config = Config::new();
        config.client_certificate("/tmp/client.pem", "/tmp/client.key");

        let dbg = format!("{:?}", config.get_client_certificate().unwrap().source);
        assert!(dbg.contains("CertAndKey"));
        assert!(dbg.contains("client.pem"));
        assert!(dbg.contains("client.key"));
    }

    #[cfg(any(feature = "native-tls", feature = "vendored-openssl"))]
    #[test]
    fn config_builder_sets_pkcs12_client_certificate() {
        let config = Config::builder()
            .client_certificate_pkcs12("/tmp/identity.pfx", "s3cr3t")
            .build();

        match &config
            .get_client_certificate()
            .expect("client certificate should be set")
            .source
        {
            ClientCertSource::Pkcs12 { path, password } => {
                assert_eq!(path, &PathBuf::from("/tmp/identity.pfx"));
                assert_eq!(password.as_str(), "s3cr3t");
            }
            other => panic!("expected Pkcs12 source, got {other:?}"),
        }
    }

    #[cfg(all(unix, feature = "sspi-rs"))]
    #[test]
    fn ado_integrated_security_sspi_with_partial_credentials_uses_windows() {
        // Only a username (no password) -> falls into the catch-all NTLM arm.
        let config = Config::from_ado_string(
            "server=tcp:localhost,1433;IntegratedSecurity=SSPI;uid=onlyuser",
        )
        .unwrap();

        match config.auth {
            AuthMethod::Windows(auth) => {
                assert_eq!("onlyuser", auth.user);
            }
            other => panic!("expected Windows auth, got {other:?}"),
        }
    }
}