tiberius 0.13.0

A TDS (MSSQL) driver
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
use super::{ConfigString, ServerDefinition};
use std::str::FromStr;

pub(crate) struct AdoNetConfig {
    dict: super::ado_parser::AdoNetString,
}

impl FromStr for AdoNetConfig {
    type Err = crate::error::Error;

    fn from_str(s: &str) -> crate::Result<Self> {
        let dict = super::ado_parser::parse(s).map_err(|reason| {
            super::hinted_conversion_error(
                reason,
                "wrap the value in single quotes (e.g. `password='p@ss;word'`), \
                 double quotes, or braces (e.g. `password={p@ss;word}`), and \
                 quote leading spaces too",
                "Config::from_ado_string",
            )
        })?;
        Ok(Self { dict })
    }
}

impl ConfigString for AdoNetConfig {
    fn dict(&self) -> &std::collections::HashMap<String, String> {
        self.dict.pairs()
    }

    fn server(&self) -> crate::Result<ServerDefinition> {
        fn parse_port(parts: &[&str]) -> crate::Result<Option<u16>> {
            Ok(match parts.first() {
                Some(s) => Some(s.parse()?),
                None => None,
            })
        }

        fn parse_server(parts: Vec<&str>) -> crate::Result<ServerDefinition> {
            if parts.is_empty() || parts.len() >= 3 {
                return Err(crate::Error::Conversion("Server value faulty.".into()));
            }

            let definition = if parts[0].contains('\\') {
                let port = parse_port(&parts[1..])?;
                let parts: Vec<&str> = parts[0].split('\\').collect();

                ServerDefinition {
                    host: Some(parts[0].replace("(local)", "localhost")),
                    port,
                    instance: Some(parts[1].into()),
                }
            } else {
                // Connect using a TCP target
                ServerDefinition {
                    host: Some(parts[0].replace("(local)", "localhost")),
                    port: parse_port(&parts[1..])?,
                    instance: None,
                }
            };

            Ok(definition)
        }

        match self
            .dict
            .pairs()
            .get("server")
            .or_else(|| self.dict.pairs().get("data source"))
        {
            Some(value) if value.starts_with("tcp:") => {
                parse_server(value[4..].split(',').collect())
            }
            Some(value) => parse_server(value.split(',').collect()),
            None => Ok(ServerDefinition {
                host: None,
                port: None,
                instance: None,
            }),
        }
    }
}

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

    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    use crate::EncryptionLevel;

    #[test]
    fn server_parsing_no_browser() -> crate::Result<()> {
        let test_str = "server=tcp:my-server.com,4200";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(Some(4200), server.port);
        assert_eq!(None, server.instance);

        let test_str = "data source=tcp:my-server.com,4200";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(Some(4200), server.port);
        assert_eq!(None, server.instance);

        Ok(())
    }

    #[test]
    fn server_parsing_no_tcp() -> crate::Result<()> {
        let test_str = "server=my-server.com,4200";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(Some(4200), server.port);
        assert_eq!(None, server.instance);

        let test_str = "data source=my-server.com,4200";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(Some(4200), server.port);
        assert_eq!(None, server.instance);

        Ok(())
    }

    #[test]
    fn server_parsing_local() -> crate::Result<()> {
        let test_str = "server=tcp:(local),4200";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("localhost".to_string()), server.host);
        assert_eq!(Some(4200), server.port);
        assert_eq!(None, server.instance);

        let test_str = "data source=tcp:(local),4200";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("localhost".to_string()), server.host);
        assert_eq!(Some(4200), server.port);
        assert_eq!(None, server.instance);

        Ok(())
    }

    #[test]
    fn server_parsing_local_no_tcp() -> crate::Result<()> {
        let test_str = "server=(local),4200";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("localhost".to_string()), server.host);
        assert_eq!(Some(4200), server.port);
        assert_eq!(None, server.instance);

        let test_str = "data source=(local),4200";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("localhost".to_string()), server.host);
        assert_eq!(Some(4200), server.port);
        assert_eq!(None, server.instance);

        Ok(())
    }

    #[test]
    fn server_parsing_no_port() -> crate::Result<()> {
        let test_str = "server=tcp:my-server.com";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(None, server.port);
        assert_eq!(None, server.instance);

        let test_str = "server=my-server.com";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(None, server.port);
        assert_eq!(None, server.instance);

        Ok(())
    }

    #[test]
    fn server_parsing_with_browser() -> crate::Result<()> {
        let test_str = "server=tcp:my-server.com\\TIBERIUS";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(None, server.port);
        assert_eq!(Some("TIBERIUS".to_string()), server.instance);

        let test_str = "data source=tcp:my-server.com\\TIBERIUS";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(None, server.port);
        assert_eq!(Some("TIBERIUS".to_string()), server.instance);

        Ok(())
    }

    #[test]
    fn server_parsing_with_browser_and_port() -> crate::Result<()> {
        let test_str = "server=tcp:my-server.com\\TIBERIUS,666";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(Some(666), server.port);
        assert_eq!(Some("TIBERIUS".to_string()), server.instance);

        let test_str = "data source=tcp:my-server.com\\TIBERIUS,666";
        let ado: AdoNetConfig = test_str.parse()?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(Some(666), server.port);
        assert_eq!(Some("TIBERIUS".to_string()), server.instance);

        Ok(())
    }

    #[test]
    fn server_parsing_too_many_parts_is_error() -> crate::Result<()> {
        // The Server value must have at most two comma-separated parts
        // (host[,port]). Three parts is invalid and must error. The guard is
        // `parts.is_empty() || parts.len() >= 3`; a `&&` mutation would never
        // trigger (a slice cannot be both empty and have >= 3 parts), so this
        // three-part value would be wrongly accepted.
        let ado: AdoNetConfig = "server=tcp:my-server.com,1433,extra".parse()?;
        assert!(ado.server().is_err());

        let ado: AdoNetConfig = "server=my-server.com,1433,extra".parse()?;
        assert!(ado.server().is_err());

        Ok(())
    }

    #[test]
    fn server_parsing_missing_key() -> crate::Result<()> {
        // No `server`/`data source` key at all -> an all-`None` definition.
        let ado: AdoNetConfig = "database=Foo".parse()?;
        let server = ado.server()?;

        assert_eq!(None, server.host);
        assert_eq!(None, server.port);
        assert_eq!(None, server.instance);

        // And the same path through the public constructor.
        let config = crate::Config::from_ado_string("database=Foo")?;
        assert_eq!("localhost", config.get_host());

        Ok(())
    }

    #[test]
    fn database_parsing() -> crate::Result<()> {
        let test_str = "database=Foo";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(Some("Foo".to_string()), ado.database());

        let test_str = "databaseName=Foo";
        let jdbc: AdoNetConfig = test_str.parse()?;

        assert_eq!(Some("Foo".to_string()), jdbc.database());

        let test_str = "Initial Catalog=Foo";
        let jdbc: AdoNetConfig = test_str.parse()?;

        assert_eq!(Some("Foo".to_string()), jdbc.database());

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_true() -> crate::Result<()> {
        let test_str = "TrustServerCertificate=true";
        let ado: AdoNetConfig = test_str.parse()?;

        assert!(ado.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_false() -> crate::Result<()> {
        let test_str = "TrustServerCertificate=false";
        let ado: AdoNetConfig = test_str.parse()?;

        assert!(!ado.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_yes() -> crate::Result<()> {
        let test_str = "TrustServerCertificate=yes";
        let ado: AdoNetConfig = test_str.parse()?;

        assert!(ado.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_no() -> crate::Result<()> {
        let test_str = "TrustServerCertificate=no";
        let ado: AdoNetConfig = test_str.parse()?;

        assert!(!ado.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_missing() -> crate::Result<()> {
        let test_str = "Something=foo;";
        let ado: AdoNetConfig = test_str.parse()?;

        assert!(!ado.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_faulty() -> crate::Result<()> {
        let test_str = "TrustServerCertificate=musti;";
        let ado: AdoNetConfig = test_str.parse()?;

        assert!(ado.trust_cert().is_err());

        Ok(())
    }

    #[test]
    fn trust_cert_ca_parsing_ok() -> crate::Result<()> {
        let test_str = "TrustServerCertificateCA=someca.crt;";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(Some("someca.crt".to_string()), ado.trust_cert_ca());

        Ok(())
    }

    #[test]
    fn parsing_sql_server_authentication() -> crate::Result<()> {
        let test_str = "uid=Musti; pwd=Naukio;";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(
            AuthMethod::sql_server("Musti", "Naukio"),
            ado.authentication()?
        );

        Ok(())
    }

    #[test]
    #[cfg(windows)]
    fn parsing_sspi_authentication() -> crate::Result<()> {
        let test_str = "IntegratedSecurity=SSPI;";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(AuthMethod::Integrated, ado.authentication()?);

        let test_str = "Integrated Security=SSPI;";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(AuthMethod::Integrated, ado.authentication()?);

        Ok(())
    }

    #[test]
    #[cfg(all(feature = "integrated-auth-gssapi", unix))]
    fn parsing_sspi_authentication() -> crate::Result<()> {
        let test_str = "IntegratedSecurity=true;";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(AuthMethod::Integrated, ado.authentication()?);

        let test_str = "Integrated Security=true;";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(AuthMethod::Integrated, ado.authentication()?);

        Ok(())
    }

    #[test]
    #[cfg(windows)]
    fn parsing_windows_authentication() -> crate::Result<()> {
        let test_str = "uid=Musti;pwd=Naukio; IntegratedSecurity=SSPI;";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(
            AuthMethod::windows("Musti", "Naukio"),
            ado.authentication()?
        );

        let test_str = "uid=Musti;pwd=Naukio; Integrated Security=SSPI;";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(
            AuthMethod::windows("Musti", "Naukio"),
            ado.authentication()?
        );

        Ok(())
    }

    #[test]
    fn parsing_database() -> crate::Result<()> {
        let test_str = "database=Cats;";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(Some("Cats".to_string()), ado.database());

        Ok(())
    }

    #[test]
    fn parsing_login_credentials_escaping() -> crate::Result<()> {
        let test_str = "User ID=musti; Password='abc;}45';";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(
            AuthMethod::sql_server("musti", "abc;}45"),
            ado.authentication()?
        );

        Ok(())
    }

    #[test]
    fn parsing_password_special_characters() -> crate::Result<()> {
        // (value as written in the connection string, exact parsed password).
        // The user and password must both round-trip exactly.
        let cases: &[(&str, &str)] = &[
            // Single quotes: the most general escape; any ASCII char except a
            // literal single quote can appear verbatim.
            ("'a;b'", "a;b"),
            ("'a=b'", "a=b"),
            ("'a{b'", "a{b"),
            ("'a}b'", "a}b"),
            ("'a b'", "a b"),
            ("'a$b'", "a$b"),
            ("'a@b'", "a@b"),
            ("'a!b'", "a!b"),
            ("'a#b'", "a#b"),
            ("'a%b'", "a%b"),
            ("'a&b'", "a&b"),
            ("'a,b'", "a,b"),
            ("'a\"b'", "a\"b"), // a double quote inside single quotes
            ("'p@ss;w{}rd=42'", "p@ss;w{}rd=42"),
            // Double quotes: same idea, and lets a single quote appear.
            ("\"a'b\"", "a'b"),
            ("\"a;b=c\"", "a;b=c"),
            // Braces (`{...}`): handy for `;` and `=`, but cannot hold a `}`.
            ("{a;b}", "a;b"),
            ("{a=b}", "a=b"),
            ("{a$b}", "a$b"),
            // Unquoted: non-structural characters pass through untouched.
            ("a$b", "a$b"),
            ("a@b", "a@b"),
            ("a!b", "a!b"),
            ("a#b", "a#b"),
            ("a%b", "a%b"),
            ("a&b", "a&b"),
            ("a,b", "a,b"),
            // A bare `}` is not structural: it passes through unquoted.
            ("a}b", "a}b"),
            // Percent-encoding is NOT decoded: `%24` stays literal, it does
            // not become `$`.
            ("a%24b", "a%24b"),
            // An empty password is accepted by the ADO parser.
            ("", ""),
        ];

        for (value, expected) in cases {
            let s = format!("User Id=sa;Password={value};");
            let ado: AdoNetConfig = s.parse()?;
            assert_eq!(
                AuthMethod::sql_server("sa", *expected),
                ado.authentication()?,
                "value `{value}` should parse to password `{expected}`"
            );
        }

        Ok(())
    }

    #[test]
    fn parsing_password_whitespace_quirks() -> crate::Result<()> {
        // Quoting preserves surrounding whitespace (matching ADO.NET): both a
        // leading and a trailing space inside quotes survive.
        let ado: AdoNetConfig = "User Id=sa;Password='a '".parse()?;
        assert_eq!(AuthMethod::sql_server("sa", "a "), ado.authentication()?);

        let ado: AdoNetConfig = "User Id=sa;Password=' a'".parse()?;
        assert_eq!(AuthMethod::sql_server("sa", " a"), ado.authentication()?);

        // An unquoted value is trimmed on both sides.
        let ado: AdoNetConfig = "User Id=sa;Password=  a  ".parse()?;
        assert_eq!(AuthMethod::sql_server("sa", "a"), ado.authentication()?);

        // Internal tabs survive.
        let ado: AdoNetConfig = "User Id=sa;Password='a\tb'".parse()?;
        assert_eq!(AuthMethod::sql_server("sa", "a\tb"), ado.authentication()?);

        Ok(())
    }

    #[test]
    fn parsing_password_brace_cannot_hold_close_brace() -> crate::Result<()> {
        // A `{…}` value closes at the first `}` and cannot contain one: any
        // characters after that `}` are a syntax error rather than being
        // silently folded into the value.
        assert!("User Id=sa;Password={a}b}".parse::<AdoNetConfig>().is_err());

        // Use single or double quotes for passwords that contain `}`.
        let ado: AdoNetConfig = "User Id=sa;Password='a}b}'".parse()?;
        assert_eq!(AuthMethod::sql_server("sa", "a}b}"), ado.authentication()?);

        Ok(())
    }

    #[test]
    fn parsing_password_non_ascii_is_rejected() {
        // The ADO parser only accepts ASCII; non-ASCII passwords must use the
        // programmatic `Config` API instead.
        assert!("User Id=sa;Password=café".parse::<AdoNetConfig>().is_err());
        assert!("User Id=sa;Password='café'"
            .parse::<AdoNetConfig>()
            .is_err());
    }

    // Every printable-ASCII special character must be usable in a password
    // through single quotes and through double quotes, round-tripping exactly.
    // The enclosing quote is embedded by doubling it.
    #[test]
    fn parsing_password_every_special_char_via_quotes() -> crate::Result<()> {
        const SPECIALS: &str = "!@#$%^&*()-_+=[]{}|\\:;\"'<>,.?/~` ";
        for c in SPECIALS.chars() {
            let expected = format!("Pa{c}ss1");

            // Single quotes: a literal `'` is written as `''`.
            let inner = if c == '\'' {
                "Pa''ss1".to_string()
            } else {
                format!("Pa{c}ss1")
            };
            let s = format!("User Id=sa;Password='{inner}'");
            let ado: AdoNetConfig = s
                .parse()
                .unwrap_or_else(|e| panic!("char {c:?} single-quoted failed: {e}"));
            assert_eq!(
                AuthMethod::sql_server("sa", expected.as_str()),
                ado.authentication()?,
                "char {c:?} single-quoted"
            );

            // Double quotes: a literal `"` is written as `""`.
            let inner = if c == '"' {
                "Pa\"\"ss1".to_string()
            } else {
                format!("Pa{c}ss1")
            };
            let s = format!("User Id=sa;Password=\"{inner}\"");
            let ado: AdoNetConfig = s
                .parse()
                .unwrap_or_else(|e| panic!("char {c:?} double-quoted failed: {e}"));
            assert_eq!(
                AuthMethod::sql_server("sa", expected.as_str()),
                ado.authentication()?,
                "char {c:?} double-quoted"
            );
        }

        Ok(())
    }

    // A doubled enclosing quote embeds that quote character.
    #[test]
    fn parsing_password_doubled_quotes_embed_the_quote() -> crate::Result<()> {
        let ado: AdoNetConfig = "User Id=sa;Password='a''b'".parse()?;
        assert_eq!(AuthMethod::sql_server("sa", "a'b"), ado.authentication()?);

        let ado: AdoNetConfig = "User Id=sa;Password=\"a\"\"b\"".parse()?;
        assert_eq!(AuthMethod::sql_server("sa", "a\"b"), ado.authentication()?);

        Ok(())
    }

    // An unquoted value may contain `=` — each pair splits on the first `=` —
    // so a base64/generated password with `=` padding parses (issue #313).
    #[test]
    fn issue_313_unquoted_equals_in_password_parses() -> crate::Result<()> {
        let cases: &[(&str, &str)] = &[
            ("Zm9vYmFy==", "Zm9vYmFy=="), // base64 with `==` padding (the report)
            ("aGVsbG8=", "aGVsbG8="),     // base64 with a single `=` pad
            ("Pa=ss1", "Pa=ss1"),
            ("a=b=c", "a=b=c"),
        ];
        for (raw, expected) in cases {
            let s =
                format!("Server=tcp:host.example.com,1433;Database=DB;User Id=sa;Password={raw}");
            let ado: AdoNetConfig = s
                .parse()
                .unwrap_or_else(|e| panic!("unquoted `{raw}` should parse: {e}"));
            assert_eq!(
                AuthMethod::sql_server("sa", *expected),
                ado.authentication()?,
                "unquoted `{raw}`"
            );
        }

        Ok(())
    }

    // `==` in the key position is a literal `=`; the pair still splits on the
    // first *single* `=`.
    #[test]
    fn parsing_key_double_equals_is_literal() -> crate::Result<()> {
        let ado: AdoNetConfig = "User Id=sa;Password=p".parse()?;
        assert_eq!(AuthMethod::sql_server("sa", "p"), ado.authentication()?);
        // A hypothetical key containing `=` round-trips via `==`.
        let cfg: AdoNetConfig = "a==b=c".parse()?;
        assert_eq!(cfg.dict.pairs().get("a=b").map(String::as_str), Some("c"));

        Ok(())
    }

    // Characters that remain genuinely ambiguous unquoted must still error and
    // point the caller at quoting — never silently mis-parse.
    #[test]
    fn parsing_password_ambiguous_unquoted_chars_error() {
        // `;` is the separator; `Password=a;b` is read as a pair `a` then a
        // second pair `b` with no `=`.
        assert!("User Id=sa;Password=a;b".parse::<AdoNetConfig>().is_err());
        // A value that *starts* with a quote/brace but is not closed is an error.
        assert!("User Id=sa;Password='ab".parse::<AdoNetConfig>().is_err());
        assert!("User Id=sa;Password=\"ab".parse::<AdoNetConfig>().is_err());
        assert!("User Id=sa;Password={ab".parse::<AdoNetConfig>().is_err());
    }

    #[test]
    fn unquoted_special_char_password_error_has_hint() {
        // An unquoted `;` in a password breaks parsing. The error must guide
        // the user toward quoting or the programmatic API while preserving the
        // underlying parser message.
        let err = "User Id=sa;Password=a;b"
            .parse::<AdoNetConfig>()
            .err()
            .unwrap();
        let msg = err.to_string();
        // Underlying terse parser message is preserved (not replaced).
        assert!(msg.contains("must be joined"), "message was: {msg}");
        // Hint mentions the ADO quoting styles and the programmatic API.
        assert!(msg.contains("single quotes"), "message was: {msg}");
        assert!(msg.contains("braces"), "message was: {msg}");
        assert!(
            msg.contains("Config::from_ado_string"),
            "message was: {msg}"
        );
        // The `Conversion error:` prefix must not be doubled.
        assert!(
            !msg.contains("Conversion error: Conversion error:"),
            "message was: {msg}"
        );
    }

    #[test]
    fn unclosed_quote_and_brace_errors_have_hint() {
        // Unclosed quote/brace are quoting mistakes; the hint should attach.
        for input in [
            "User Id=sa;Password='abc",  // unclosed single quote
            "User Id=sa;Password=\"abc", // unclosed double quote
            "User Id=sa;Password={abc",  // unclosed brace
        ] {
            let err = input.parse::<AdoNetConfig>().err().unwrap();
            let msg = err.to_string();
            assert!(msg.contains("must be quoted"), "message was: {msg}");
            assert!(
                !msg.contains("Conversion error: Conversion error:"),
                "message was: {msg}"
            );
        }
    }

    #[test]
    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    fn encryption_parsing_on() -> crate::Result<()> {
        let test_str = "encrypt=true";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(EncryptionLevel::Required, ado.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    fn encryption_parsing_off() -> crate::Result<()> {
        let test_str = "encrypt=false";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(EncryptionLevel::Off, ado.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    fn encryption_parsing_plaintext() -> crate::Result<()> {
        let test_str = "encrypt=DANGER_PLAINTEXT";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(EncryptionLevel::NotSupported, ado.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    ))]
    fn encryption_parsing_missing() -> crate::Result<()> {
        let test_str = "";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(EncryptionLevel::Required, ado.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(feature = "tds80")]
    fn encryption_parsing_strict() -> crate::Result<()> {
        let test_str = "encrypt=strict";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(EncryptionLevel::Strict, ado.encrypt()?);

        Ok(())
    }

    // No-TLS build: an explicit encryption request must error (not silently
    // downgrade to plaintext, #305); opting out and an omitted keyword stay
    // `NotSupported`.

    #[test]
    #[cfg(not(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    )))]
    fn encryption_parsing_on_errors_without_tls_backend() -> crate::Result<()> {
        for test_str in ["encrypt=true", "encrypt=yes"] {
            let ado: AdoNetConfig = test_str.parse()?;
            let err = ado.encrypt().unwrap_err();
            assert!(
                matches!(err, crate::Error::Tls(_)),
                "expected Error::Tls for {test_str}, got {err:?}"
            );
            let msg = err.to_string();
            assert!(msg.contains("without a TLS backend"), "message was: {msg}");
        }

        Ok(())
    }

    #[test]
    #[cfg(not(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    )))]
    fn encryption_parsing_strict_errors_without_tls_backend() {
        let ado: AdoNetConfig = "encrypt=strict".parse().unwrap();
        let err = ado.encrypt().unwrap_err();
        assert!(
            matches!(err, crate::Error::Tls(_)),
            "expected Error::Tls, got {err:?}"
        );
    }

    #[test]
    #[cfg(not(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    )))]
    fn encryption_parsing_mandatory_errors_without_tls_backend() {
        // `mandatory` is not an accepted token in either build; the with-TLS
        // parser rejects it as a bad boolean, so the no-TLS branch mirrors that
        // (still an error, just not the TLS-missing one).
        let ado: AdoNetConfig = "encrypt=mandatory".parse().unwrap();
        assert!(ado.encrypt().is_err());
    }

    #[test]
    #[cfg(not(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    )))]
    fn encryption_parsing_off_ok_without_tls_backend() -> crate::Result<()> {
        for test_str in ["encrypt=false", "encrypt=no"] {
            let ado: AdoNetConfig = test_str.parse()?;
            assert_eq!(crate::EncryptionLevel::NotSupported, ado.encrypt()?);
        }

        Ok(())
    }

    #[test]
    #[cfg(not(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    )))]
    fn encryption_parsing_plaintext_ok_without_tls_backend() -> crate::Result<()> {
        let ado: AdoNetConfig = "encrypt=DANGER_PLAINTEXT".parse()?;
        assert_eq!(crate::EncryptionLevel::NotSupported, ado.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(not(any(
        feature = "rustls",
        feature = "native-tls",
        feature = "vendored-openssl"
    )))]
    fn encryption_parsing_missing_ok_without_tls_backend() -> crate::Result<()> {
        let ado: AdoNetConfig = "".parse()?;
        assert_eq!(crate::EncryptionLevel::NotSupported, ado.encrypt()?);

        Ok(())
    }

    #[test]
    fn client_name_parsing() -> crate::Result<()> {
        let test_str = "workstationid=meow";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(Some("meow".into()), ado.client_name());

        let test_str = "Workstation ID=meow";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(Some("meow".into()), ado.client_name());

        Ok(())
    }

    #[test]
    fn hostname_in_certificate_parsing() -> crate::Result<()> {
        let test_str = "HostNameInCertificate=foo.example.com";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(
            Some("foo.example.com".into()),
            ado.hostname_in_certificate()
        );

        let test_str = "HostName In Certificate=foo.example.com";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(
            Some("foo.example.com".into()),
            ado.hostname_in_certificate()
        );

        Ok(())
    }

    #[test]
    fn application_name_parsing() -> crate::Result<()> {
        let test_str = "Application Name=meow";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(Some("meow".into()), ado.application_name());

        let test_str = "ApplicationName=meow";
        let ado: AdoNetConfig = test_str.parse()?;

        assert_eq!(Some("meow".into()), ado.application_name());

        Ok(())
    }

    #[test]
    fn application_intent_readonly_parsing() -> crate::Result<()> {
        // Exact spelling from the ADO.NET connection string.
        let ado: AdoNetConfig = "ApplicationIntent=ReadOnly".parse()?;
        assert!(ado.readonly());

        // ADO.NET treats the value case-insensitively.
        let ado: AdoNetConfig = "applicationintent=readonly".parse()?;
        assert!(ado.readonly());

        // ReadWrite (the default) must not request read-only intent.
        let ado: AdoNetConfig = "ApplicationIntent=ReadWrite".parse()?;
        assert!(!ado.readonly());

        // Absent altogether.
        let ado: AdoNetConfig = "server=tcp:localhost,1433".parse()?;
        assert!(!ado.readonly());

        Ok(())
    }

    #[test]
    fn multi_subnet_failover_parsing() -> crate::Result<()> {
        let test_str = "MultiSubnetFailover=true";
        let ado: AdoNetConfig = test_str.parse()?;
        assert!(ado.multi_subnet_failover()?);

        let test_str = "MultiSubnetFailover=yes";
        let ado: AdoNetConfig = test_str.parse()?;
        assert!(ado.multi_subnet_failover()?);

        let test_str = "MultiSubnetFailover=false";
        let ado: AdoNetConfig = test_str.parse()?;
        assert!(!ado.multi_subnet_failover()?);

        Ok(())
    }

    #[test]
    fn multi_subnet_failover_parsing_missing() -> crate::Result<()> {
        let test_str = "";
        let ado: AdoNetConfig = test_str.parse()?;
        assert!(!ado.multi_subnet_failover()?);

        Ok(())
    }

    #[test]
    fn multi_subnet_failover_from_ado_string() -> crate::Result<()> {
        let config = crate::Config::from_ado_string(
            "server=tcp:my-server.com,1433;MultiSubnetFailover=true",
        )?;
        assert!(config.get_multi_subnet_failover());

        let config = crate::Config::from_ado_string("server=tcp:my-server.com,1433")?;
        assert!(!config.get_multi_subnet_failover());

        Ok(())
    }
}