mssql-tds 0.1.0

Rust implementation of the TDS (Tabular Data Stream) protocol for SQL Server
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

pub mod bulk_copy_errors;

use std::path::PathBuf;

pub use bulk_copy_errors::{BulkCopyAttentionTimeoutError, BulkCopyError, BulkCopyTimeoutError};

use crate::security::SecurityError;
use thiserror::Error;
use tokio::time::error::Elapsed;

/// A single SQL Server error, analogous to SqlClient's `SqlError`.
///
/// SQL Server can return multiple errors for a single batch execution.
/// This struct represents one error from the stream. The full collection
/// is available via [`SqlServerDiagnostics`] inside `Error::SqlServerError`.
#[derive(Debug, Clone)]
pub struct SqlErrorInfo {
    /// Error message text returned by the server.
    pub message: String,
    /// Error state, used by the server to indicate specific error conditions.
    pub state: u8,
    /// Severity class of the error (maps to TDS `Class` field).
    pub class: i32,
    /// Server-defined error number.
    pub number: u32,
    /// Name of the server that generated the error.
    pub server_name: Option<String>,
    /// Name of the stored procedure that generated the error.
    pub proc_name: Option<String>,
    /// Line number in the batch or procedure where the error occurred.
    pub line_number: Option<i32>,
}

impl std::fmt::Display for SqlErrorInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Sql Error: {}: Class {}: State {}: {} on {} in {} at line {}",
            self.number,
            self.class,
            self.state,
            self.message,
            self.server_name.as_deref().unwrap_or("Unknown"),
            self.proc_name.as_deref().unwrap_or("Unknown"),
            self.line_number.unwrap_or_default()
        )
    }
}

impl From<&crate::token::tokens::ErrorToken> for SqlErrorInfo {
    fn from(token: &crate::token::tokens::ErrorToken) -> Self {
        Self {
            message: token.message.clone(),
            state: token.state,
            class: token.severity as i32,
            number: token.number,
            server_name: Some(token.server_name.clone()),
            proc_name: Some(token.proc_name.clone()),
            line_number: Some(token.line_number as i32),
        }
    }
}

/// A single informational message returned by SQL Server.
///
/// SQL Server can return multiple INFO tokens for one request. These tokens
/// carry warning or informational messages such as PRINT output, database or
/// language changes, and low-severity RAISERROR output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SqlInfoMessage {
    /// Message text returned by the server.
    pub message: String,
    /// Message state, used by the server to indicate specific conditions.
    pub state: u8,
    /// Severity class of the message (maps to TDS `Class` field).
    pub class: i32,
    /// Server-defined message number.
    pub number: u32,
    /// Name of the server that generated the message.
    pub server_name: Option<String>,
    /// Name of the stored procedure that generated the message.
    pub proc_name: Option<String>,
    /// Line number in the batch or procedure where the message occurred.
    pub line_number: Option<i32>,
}

impl From<&crate::token::tokens::InfoToken> for SqlInfoMessage {
    fn from(token: &crate::token::tokens::InfoToken) -> Self {
        Self {
            message: token.message.clone(),
            state: token.state,
            class: token.severity as i32,
            number: token.number,
            server_name: Some(token.server_name.clone()),
            proc_name: Some(token.proc_name.clone()),
            line_number: Some(token.line_number as i32),
        }
    }
}

/// Diagnostics reported by SQL Server for a single operation.
///
/// SQL Server can send multiple `ERROR` and `INFO` tokens for one request
/// (batch, RPC, or login). This groups both categories so a failed operation
/// can carry the complete server-reported diagnostic set — errors that caused
/// the failure plus any informational/warning messages that preceded them —
/// rather than only the first error.
#[derive(Debug, Clone, Default)]
pub struct SqlServerDiagnostics {
    /// Server-reported errors, in the order TDS delivered them.
    pub errors: Vec<SqlErrorInfo>,
    /// Server-reported informational/warning messages, in wire order.
    pub info_messages: Vec<SqlInfoMessage>,
}

impl SqlServerDiagnostics {
    /// Create a diagnostics set from errors and informational messages.
    pub fn new(errors: Vec<SqlErrorInfo>, info_messages: Vec<SqlInfoMessage>) -> Self {
        Self {
            errors,
            info_messages,
        }
    }

    /// Returns `true` if any server error was reported.
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Returns `true` if neither errors nor informational messages are present.
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty() && self.info_messages.is_empty()
    }
}

/// The source of a timeout: either a Tokio `Elapsed` or a descriptive string.
#[derive(Debug, Error)]
pub enum TimeoutErrorType {
    /// Wrapper around a Tokio `Elapsed` error.
    #[error("Elapsed: {0}")]
    Elapsed(Elapsed),

    /// Freeform timeout description.
    #[error("{0}")]
    String(String),
}

/// All errors produced by the TDS client.
#[derive(Debug, Error)]
pub enum Error {
    /// Underlying I/O failure.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// Server requested a connection redirect.
    #[error("Server redirected the connection: {host}:{port} times")]
    Redirection {
        /// Target hostname.
        host: String,
        /// Target port.
        port: u16,
    },

    /// Failed to establish a connection.
    #[error("Connection Error: {0}")]
    ConnectionError(String),

    /// TDS protocol violation or unexpected server response.
    #[error("Protocol Error: {0}")]
    ProtocolError(String),

    /// TLS/SSL library error.
    #[error("TLS Error: {0}")]
    TlsError(#[from] native_tls::Error),

    /// TLS handshake failed with host/SAN details.
    #[error(
        "TLS handshake failed while connecting to '{expected_host}': {source}. Certificate SANs: {cert_sans}"
    )]
    TlsHandshakeError {
        /// Inner TLS error.
        source: native_tls::Error,
        /// Hostname the client tried to connect to.
        expected_host: String,
        /// Subject Alternative Names found on the certificate.
        cert_sans: String,
    },

    /// Operation exceeded its deadline.
    #[error("Timeout Error: {0}")]
    TimeoutError(TimeoutErrorType),

    /// Operation was cancelled via a `CancelHandle`.
    #[error("Operation Cancelled Error: {0}")]
    OperationCancelledError(String),

    /// One or more errors returned by SQL Server, plus any informational
    /// messages that accompanied them.
    ///
    /// `diagnostics.info_messages` is only populated on the **login** path,
    /// where a failed connect has no live `TdsClient` to drain. Statement, RPC,
    /// and batch failures are built via [`Error::from_sql_errors`] and leave
    /// `info_messages` **empty**; any INFO those commands emitted is retained on
    /// the client and must be read separately via
    /// `TdsClient::take_info_messages()`.
    #[error("{}", SqlServerError::format_errors(&diagnostics.errors))]
    SqlServerError {
        /// Server-reported diagnostics (errors and informational messages).
        diagnostics: SqlServerDiagnostics,
    },

    /// Caller misused the API (e.g., invalid parameter combination).
    #[error("Usage Error: {0}")]
    UsageError(String),

    /// Internal logic error that should not occur.
    #[error("Unexpected Implementation Error: {0}")]
    ImplementationError(String),

    /// Feature recognized but not yet implemented.
    #[error("Unimplemented Feature: {feature} - {context}")]
    UnimplementedFeature {
        /// Name of the unimplemented feature.
        feature: String,
        /// Additional context.
        context: String,
    },

    /// Value could not be converted to the target SQL type.
    #[error("Type Conversion Error: {0}")]
    TypeConversionError(String),

    /// Connection was closed by server or transport.
    #[error("Connection closed: {0}")]
    ConnectionClosed(String),

    /// Code page / LCID has no mapped encoding.
    #[error(
        "Unsupported Encoding: LCID {lcid} (0x{lcid:04X}). Consider using NVARCHAR instead of VARCHAR/TEXT for better compatibility."
    )]
    UnsupportedEncoding {
        /// Windows locale ID that has no available encoding.
        lcid: u32,
    },

    /// Certificate file does not exist on disk.
    #[error(
        "Certificate file not found: {path}. Verify the ServerCertificate path is correct and the file exists."
    )]
    CertificateNotFound {
        /// File path that was looked up.
        path: PathBuf,
    },

    /// Certificate file is present but cannot be parsed.
    #[error(
        "Invalid certificate format in file: {path}. Ensure the file contains a valid DER or PEM encoded X.509 certificate."
    )]
    InvalidCertificateFormat {
        /// File path with the invalid certificate.
        path: PathBuf,
    },

    /// Server certificate has passed its validity period.
    #[error(
        "Server certificate has expired. The server's certificate is no longer valid. Contact your administrator."
    )]
    CertificateExpired,

    /// Server presented a certificate that does not match expectations.
    #[error(
        "Server certificate validation failed: Certificate mismatch. The server presented a different certificate than expected. Verify you are connecting to the correct server."
    )]
    CertificateMismatch,

    /// I/O error while reading a certificate file.
    #[error(
        "Failed to read certificate file: {path}. Error: {error}. Check file permissions and ensure the file is not locked by another process."
    )]
    CertificateFileIoError {
        /// File path that could not be read.
        path: PathBuf,
        /// Underlying I/O error message.
        error: String,
    },

    /// TLS handshake completed but server did not provide a certificate.
    #[error("No server certificate available during TLS handshake.")]
    NoServerCertificate,

    /// Error from a bulk copy operation.
    #[error("Bulk Copy Error: {0}")]
    BulkCopyError(#[from] BulkCopyError),

    /// Authentication / security subsystem error.
    #[error("Security error: {0}")]
    Security(#[from] SecurityError),

    /// All reconnection attempts exhausted.
    #[error("Session recovery failed after {attempts} attempt(s): {message}")]
    SessionRecoveryFailed {
        /// Number of reconnection attempts made.
        attempts: u32,
        /// Description of the final failure.
        message: String,
    },

    /// Session state prevents reconnection (transactions, unrecoverable state).
    #[error("Session not recoverable: {0}")]
    SessionNotRecoverable(String),

    /// Reconnected server properties don't match original.
    #[error("Reconnection validation failed: {0}")]
    ReconnectionValidationFailed(String),

    /// Cryptographic failure in the Always Encrypted column-encryption data path.
    #[error("Column encryption error: {0}")]
    ColumnEncryptionError(String),

    /// A request carried the RESETCONNECTION packet-header bit, but its response
    /// never contained the `ResetConnection` ENVCHANGE. The session was
    /// therefore never returned to its login defaults and must not be reused.
    #[error(
        "The connection reset was not acknowledged by the server, so the session was not returned to its login defaults"
    )]
    ConnectionResetNotAcknowledged,
}

/// Helper for `SqlServerError` display formatting.
struct SqlServerError;

impl SqlServerError {
    fn format_errors(errors: &[SqlErrorInfo]) -> String {
        match errors.len() {
            0 => "Sql Error: (no error details)".to_string(),
            1 => errors[0].to_string(),
            _ => errors
                .iter()
                .map(|e| e.to_string())
                .collect::<Vec<_>>()
                .join("\n"),
        }
    }
}

/// SQL Server error numbers that indicate a transient condition during
/// connection open. These are server-reported errors where retrying the
/// connection may succeed.
///
/// This list is the intersection of the transient error sets used by
/// SqlClient (`s_defaultTransientErrors` in `SqlConfigurableRetryFactory.cs`)
/// and JDBC (`TransientError` enum in `SQLServerError.java`).
///
/// Transport-level transient errors (JDBC codes 64, 10053, 10054) are already
/// covered by [`Error::Io`] and [`Error::ConnectionClosed`] variants.
const TRANSIENT_SQL_ERROR_NUMBERS: &[u32] = &[
    233,   // Connection closed by remote host / no process on other end of pipe
    4060,  // Cannot open database requested by the login
    4221,  // Login to read-secondary failed (HADR transition timeout)
    10928, // Resource limit reached (Azure SQL)
    10929, // Resource minimum guarantee exceeded (Azure SQL)
    40143, // Service error processing request
    40197, // Service error during upgrades/failover (may embed 40020/40143/40166/40540)
    40501, // Service busy — retry after 10 seconds
    40540, // Service error processing request
    40613, // Database not currently available
    42108, // SQL pool paused (Synapse)
    42109, // SQL pool warming up (Synapse)
    49918, // Not enough resources to process request
    49919, // Too many create/update operations in progress
    49920, // Too many operations in progress for subscription
];

impl Error {
    /// Create a `SqlServerError` from a single `SqlErrorInfo`.
    pub fn from_sql_error(error: SqlErrorInfo) -> Self {
        Error::SqlServerError {
            diagnostics: SqlServerDiagnostics::new(vec![error], Vec::new()),
        }
    }

    /// Create a `SqlServerError` from multiple `SqlErrorInfo`s.
    pub fn from_sql_errors(errors: Vec<SqlErrorInfo>) -> Self {
        Error::SqlServerError {
            diagnostics: SqlServerDiagnostics::new(errors, Vec::new()),
        }
    }

    /// Create a `SqlServerError` from a full set of server diagnostics
    /// (errors plus informational messages).
    pub fn from_sql_diagnostics(diagnostics: SqlServerDiagnostics) -> Self {
        Error::SqlServerError { diagnostics }
    }

    /// Whether this error is transient for connection open retry purposes.
    ///
    /// Transient errors warrant retrying the entire connection sequence.
    /// Permanent errors (auth failures, TLS config, protocol violations)
    /// should not be retried.
    ///
    /// For transport-level failures (`Io`, `ConnectionError`, `TimeoutError`,
    /// `ConnectionClosed`), all instances are considered transient.
    ///
    /// For server-reported errors (`SqlServerError`), only specific error
    /// numbers known to be transient trigger a retry. See
    /// [`TRANSIENT_SQL_ERROR_NUMBERS`] for the full list.
    pub(crate) fn is_transient_connect_error(&self) -> bool {
        match self {
            Error::Io(_)
            | Error::ConnectionError(_)
            | Error::TimeoutError(_)
            | Error::ConnectionClosed(_) => true,

            Error::SqlServerError { diagnostics } => diagnostics
                .errors
                .iter()
                .any(|e| TRANSIENT_SQL_ERROR_NUMBERS.contains(&e.number)),

            _ => false,
        }
    }
}

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

    #[test]
    fn test_timeout_error_type_string() {
        let error = TimeoutErrorType::String("Test timeout".to_string());
        assert_eq!(error.to_string(), "Test timeout");
    }

    #[test]
    fn test_timeout_error_type_elapsed() {
        // Create an Elapsed error by timing out a sleep
        let rt = tokio::runtime::Runtime::new().unwrap();
        let elapsed = rt.block_on(async {
            tokio::time::timeout(std::time::Duration::from_millis(1), async {
                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            })
            .await
            .unwrap_err()
        });
        let error = TimeoutErrorType::Elapsed(elapsed);
        assert!(error.to_string().contains("Elapsed"));
    }

    #[test]
    fn test_io_error_conversion() {
        let io_error = io::Error::new(io::ErrorKind::ConnectionRefused, "Connection refused");
        let error = Error::from(io_error);
        match error {
            Error::Io(e) => assert_eq!(e.kind(), io::ErrorKind::ConnectionRefused),
            _ => panic!("Expected IO error"),
        }
    }

    #[test]
    fn test_redirection_error() {
        let error = Error::Redirection {
            host: "example.com".to_string(),
            port: 1433,
        };
        assert!(error.to_string().contains("example.com"));
        assert!(error.to_string().contains("1433"));
    }

    #[test]
    fn test_protocol_error() {
        let error = Error::ProtocolError("Invalid packet".to_string());
        assert_eq!(error.to_string(), "Protocol Error: Invalid packet");
    }

    #[test]
    fn test_timeout_error() {
        let timeout_type = TimeoutErrorType::String("Query timeout".to_string());
        let error = Error::TimeoutError(timeout_type);
        assert!(error.to_string().contains("Query timeout"));
    }

    #[test]
    fn test_operation_cancelled_error() {
        let error = Error::OperationCancelledError("User cancelled".to_string());
        assert!(error.to_string().contains("User cancelled"));
    }

    #[test]
    fn test_sql_server_error_full() {
        let error = Error::from_sql_error(SqlErrorInfo {
            message: "Login failed".to_string(),
            state: 1,
            class: 14,
            number: 18456,
            server_name: Some("SQLSERVER01".to_string()),
            proc_name: Some("sp_login".to_string()),
            line_number: Some(42),
        });
        let err_str = error.to_string();
        assert!(err_str.contains("18456"));
        assert!(err_str.contains("Login failed"));
        assert!(err_str.contains("SQLSERVER01"));
        assert!(err_str.contains("sp_login"));
        assert!(err_str.contains("42"));
    }

    #[test]
    fn test_sql_server_error_with_none_values() {
        let error = Error::from_sql_error(SqlErrorInfo {
            message: "Error occurred".to_string(),
            state: 2,
            class: 16,
            number: 50000,
            server_name: None,
            proc_name: None,
            line_number: None,
        });
        let err_str = error.to_string();
        assert!(err_str.contains("50000"));
        assert!(err_str.contains("Error occurred"));
        assert!(err_str.contains("Unknown"));
    }

    #[test]
    fn test_sql_server_error_multiple() {
        let error = Error::from_sql_errors(vec![
            SqlErrorInfo {
                message: "First error".to_string(),
                state: 1,
                class: 16,
                number: 50000,
                server_name: Some("SRV".to_string()),
                proc_name: None,
                line_number: Some(1),
            },
            SqlErrorInfo {
                message: "Second error".to_string(),
                state: 1,
                class: 16,
                number: 50001,
                server_name: Some("SRV".to_string()),
                proc_name: None,
                line_number: Some(2),
            },
        ]);
        let err_str = error.to_string();
        assert!(err_str.contains("First error"));
        assert!(err_str.contains("Second error"));
        assert!(err_str.contains("50000"));
        assert!(err_str.contains("50001"));
    }

    #[test]
    fn test_usage_error() {
        let error = Error::UsageError("Invalid connection string".to_string());
        assert_eq!(error.to_string(), "Usage Error: Invalid connection string");
    }

    #[test]
    fn test_implementation_error() {
        let error = Error::ImplementationError("Not implemented yet".to_string());
        assert_eq!(
            error.to_string(),
            "Unexpected Implementation Error: Not implemented yet"
        );
    }

    #[test]
    fn test_unimplemented_feature() {
        let error = Error::UnimplementedFeature {
            feature: "Always Encrypted".to_string(),
            context: "Column encryption not supported".to_string(),
        };
        let err_str = error.to_string();
        assert!(err_str.contains("Always Encrypted"));
        assert!(err_str.contains("Column encryption not supported"));
    }

    #[test]
    fn test_type_conversion_error() {
        let error = Error::TypeConversionError("Cannot convert VARCHAR to INT".to_string());
        assert_eq!(
            error.to_string(),
            "Type Conversion Error: Cannot convert VARCHAR to INT"
        );
    }

    #[test]
    fn test_error_debug_format() {
        let error = Error::ProtocolError("Test".to_string());
        let debug_str = format!("{error:?}");
        assert!(debug_str.contains("ProtocolError"));
    }

    // ── Transient error classification tests ──

    #[test]
    fn io_error_is_transient() {
        let err = Error::Io(io::Error::new(io::ErrorKind::ConnectionRefused, "refused"));
        assert!(err.is_transient_connect_error());
    }

    #[test]
    fn connection_error_is_transient() {
        let err = Error::ConnectionError("failed to connect".to_string());
        assert!(err.is_transient_connect_error());
    }

    #[test]
    fn timeout_error_is_transient() {
        let err = Error::TimeoutError(TimeoutErrorType::String("timed out".to_string()));
        assert!(err.is_transient_connect_error());
    }

    #[test]
    fn connection_closed_is_transient() {
        let err = Error::ConnectionClosed("reset by peer".to_string());
        assert!(err.is_transient_connect_error());
    }

    #[test]
    fn permanent_sql_server_error_is_not_transient() {
        // 18456 = Login failed — permanent, should not retry
        let err = Error::from_sql_error(SqlErrorInfo {
            message: "Login failed".to_string(),
            state: 1,
            class: 14,
            number: 18456,
            server_name: None,
            proc_name: None,
            line_number: None,
        });
        assert!(!err.is_transient_connect_error());
    }

    #[test]
    fn transient_sql_server_errors_are_retried() {
        for &code in &[
            233, 4060, 4221, 10928, 10929, 40143, 40197, 40501, 40540, 40613, 42108, 42109, 49918,
            49919, 49920,
        ] {
            let err = Error::from_sql_error(SqlErrorInfo {
                message: "transient".to_string(),
                state: 1,
                class: 16,
                number: code,
                server_name: None,
                proc_name: None,
                line_number: None,
            });
            assert!(
                err.is_transient_connect_error(),
                "SQL error {code} should be transient"
            );
        }
    }

    #[test]
    fn mixed_sql_errors_transient_if_any_match() {
        // If any error in the batch is transient, the whole error is transient
        let err = Error::from_sql_errors(vec![
            SqlErrorInfo {
                message: "Login failed".to_string(),
                state: 1,
                class: 14,
                number: 18456,
                server_name: None,
                proc_name: None,
                line_number: None,
            },
            SqlErrorInfo {
                message: "Service busy".to_string(),
                state: 1,
                class: 16,
                number: 40501,
                server_name: None,
                proc_name: None,
                line_number: None,
            },
        ]);
        assert!(err.is_transient_connect_error());
    }

    #[test]
    fn protocol_error_is_not_transient() {
        let err = Error::ProtocolError("bad packet".to_string());
        assert!(!err.is_transient_connect_error());
    }

    #[test]
    fn operation_cancelled_is_not_transient() {
        let err = Error::OperationCancelledError("cancelled".to_string());
        assert!(!err.is_transient_connect_error());
    }

    #[test]
    fn usage_error_is_not_transient() {
        let err = Error::UsageError("bad param".to_string());
        assert!(!err.is_transient_connect_error());
    }

    #[test]
    fn security_error_is_not_transient() {
        let err = Error::Security(SecurityError::NotSupported("SSPI".to_string()));
        assert!(!err.is_transient_connect_error());
    }

    #[test]
    fn authentication_denied_is_not_transient() {
        // Interactive/browser auth denials (user cancel, `invalid_grant`, …) map to
        // this variant so the connect-retry loop does not relaunch the sign-in.
        let err = Error::Security(SecurityError::AuthenticationDenied(
            "access_denied".to_string(),
        ));
        assert!(!err.is_transient_connect_error());
    }

    // ── SqlServerDiagnostics wrapper ──

    fn sample_error(number: u32, message: &str) -> SqlErrorInfo {
        SqlErrorInfo {
            message: message.to_string(),
            state: 1,
            class: 16,
            number,
            server_name: None,
            proc_name: None,
            line_number: None,
        }
    }

    fn sample_info(number: u32, message: &str) -> SqlInfoMessage {
        SqlInfoMessage {
            message: message.to_string(),
            state: 1,
            class: 10,
            number,
            server_name: None,
            proc_name: None,
            line_number: None,
        }
    }

    #[test]
    fn diagnostics_helpers_report_contents() {
        let empty = SqlServerDiagnostics::default();
        assert!(empty.is_empty());
        assert!(!empty.has_errors());

        let info_only = SqlServerDiagnostics::new(vec![], vec![sample_info(5701, "db context")]);
        assert!(!info_only.is_empty());
        assert!(!info_only.has_errors());

        let with_errors =
            SqlServerDiagnostics::new(vec![sample_error(18456, "login failed")], vec![]);
        assert!(!with_errors.is_empty());
        assert!(with_errors.has_errors());
    }

    #[test]
    fn from_sql_diagnostics_preserves_errors_and_info() {
        let diagnostics = SqlServerDiagnostics::new(
            vec![sample_error(18456, "login failed")],
            vec![sample_info(5701, "changed database context")],
        );
        let err = Error::from_sql_diagnostics(diagnostics);
        match &err {
            Error::SqlServerError { diagnostics } => {
                assert_eq!(diagnostics.errors.len(), 1);
                assert_eq!(diagnostics.errors[0].number, 18456);
                assert_eq!(diagnostics.info_messages.len(), 1);
                assert_eq!(diagnostics.info_messages[0].number, 5701);
            }
            other => panic!("Expected SqlServerError, got: {other:?}"),
        }
        // Display surfaces the error text (info messages are diagnostics, not the failure reason).
        assert!(err.to_string().contains("login failed"));
    }

    #[test]
    fn diagnostics_transient_detection_reads_errors() {
        // 40501 is transient; the wrapper must still classify it as such.
        let err = Error::from_sql_diagnostics(SqlServerDiagnostics::new(
            vec![sample_error(40501, "service busy")],
            vec![sample_info(5701, "db context")],
        ));
        assert!(err.is_transient_connect_error());
    }
}