sqlmodel-core 0.2.0

Core types and traits for SQLModel Rust
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
//! Error types for SQLModel operations.

use std::fmt;

/// The primary error type for all SQLModel operations.
#[derive(Debug)]
pub enum Error {
    /// Connection-related errors (connect, disconnect, timeout)
    Connection(ConnectionError),
    /// Query execution errors
    Query(QueryError),
    /// Type conversion errors
    Type(TypeError),
    /// Transaction errors
    Transaction(TransactionError),
    /// Protocol errors (wire-level)
    Protocol(ProtocolError),
    /// Pool errors
    Pool(PoolError),
    /// Schema/migration errors
    Schema(SchemaError),
    /// Configuration errors
    Config(ConfigError),
    /// Validation errors
    Validation(ValidationError),
    /// I/O errors
    Io(std::io::Error),
    /// Operation timed out
    Timeout,
    /// Operation was cancelled via asupersync
    Cancelled,
    /// Serialization/deserialization errors
    Serde(String),
    /// Custom error with message
    Custom(String),
}

#[derive(Debug)]
pub struct ConnectionError {
    pub kind: ConnectionErrorKind,
    pub message: String,
    pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectionErrorKind {
    /// Failed to establish connection
    Connect,
    /// Authentication failed
    Authentication,
    /// Connection lost during operation
    Disconnected,
    /// SSL/TLS negotiation failed
    Ssl,
    /// DNS resolution failed
    DnsResolution,
    /// Connection refused
    Refused,
    /// Connection pool exhausted
    PoolExhausted,
}

#[derive(Debug)]
pub struct QueryError {
    pub kind: QueryErrorKind,
    pub sql: Option<String>,
    pub sqlstate: Option<String>,
    pub message: String,
    pub detail: Option<String>,
    pub hint: Option<String>,
    pub position: Option<usize>,
    pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueryErrorKind {
    /// Syntax error in SQL
    Syntax,
    /// Constraint violation (unique, foreign key, etc.)
    Constraint,
    /// Table or column not found
    NotFound,
    /// Permission denied
    Permission,
    /// Data too large for column
    DataTruncation,
    /// Deadlock detected
    Deadlock,
    /// Serialization failure (retry may succeed)
    Serialization,
    /// Statement timeout
    Timeout,
    /// Cancelled
    Cancelled,
    /// Other database error
    Database,
}

#[derive(Debug)]
pub struct TypeError {
    pub expected: &'static str,
    pub actual: String,
    pub column: Option<String>,
    pub rust_type: Option<&'static str>,
}

#[derive(Debug)]
pub struct TransactionError {
    pub kind: TransactionErrorKind,
    pub message: String,
}

#[derive(Debug, Clone, Copy)]
pub enum TransactionErrorKind {
    /// Already committed
    AlreadyCommitted,
    /// Already rolled back
    AlreadyRolledBack,
    /// Savepoint not found
    SavepointNotFound,
    /// Nested transaction not supported
    NestedNotSupported,
}

#[derive(Debug)]
pub struct ProtocolError {
    pub message: String,
    pub raw_data: Option<Vec<u8>>,
    pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

#[derive(Debug)]
pub struct PoolError {
    pub kind: PoolErrorKind,
    pub message: String,
    pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

impl PoolError {
    /// Create a new pool error indicating the internal mutex was poisoned.
    ///
    /// The `operation` parameter should describe what operation was being attempted
    /// when the poisoned lock was encountered (e.g., "acquire", "close", "stats").
    pub fn poisoned(operation: &str) -> Self {
        Self {
            kind: PoolErrorKind::Poisoned,
            message: format!(
                "pool mutex poisoned during {operation}; a thread panicked while holding the lock"
            ),
            source: None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PoolErrorKind {
    /// Pool exhausted (no available connections)
    Exhausted,
    /// Connection checkout timeout
    Timeout,
    /// Pool is closed
    Closed,
    /// Configuration error
    Config,
    /// Internal mutex was poisoned (a thread panicked while holding the lock)
    ///
    /// This indicates a serious internal error. The pool may still be usable
    /// for read-only operations, but mutation operations will fail.
    Poisoned,
}

#[derive(Debug)]
pub struct SchemaError {
    pub kind: SchemaErrorKind,
    pub message: String,
    pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

#[derive(Debug, Clone, Copy)]
pub enum SchemaErrorKind {
    /// Table already exists
    TableExists,
    /// Table not found
    TableNotFound,
    /// Column already exists
    ColumnExists,
    /// Column not found
    ColumnNotFound,
    /// Invalid schema definition
    Invalid,
    /// Migration error
    Migration,
}

#[derive(Debug)]
pub struct ConfigError {
    pub message: String,
    pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

/// Validation error for field-level and model-level validation.
#[derive(Debug, Clone)]
pub struct ValidationError {
    /// The errors grouped by field name (or "_model" for model-level)
    pub errors: Vec<FieldValidationError>,
}

/// A single validation error for a field.
#[derive(Debug, Clone)]
pub struct FieldValidationError {
    /// The field name that failed validation
    pub field: String,
    /// The kind of validation that failed
    pub kind: ValidationErrorKind,
    /// Human-readable error message
    pub message: String,
}

/// The type of validation constraint that was violated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidationErrorKind {
    /// Value is below minimum
    Min,
    /// Value is above maximum
    Max,
    /// String is shorter than minimum length
    MinLength,
    /// String is longer than maximum length
    MaxLength,
    /// Value doesn't match regex pattern
    Pattern,
    /// Required field is missing/null
    Required,
    /// Custom validation failed
    Custom,
    /// Model-level validation failed
    Model,
    /// Value is not a multiple of the specified divisor
    MultipleOf,
    /// Collection has fewer items than minimum
    MinItems,
    /// Collection has more items than maximum
    MaxItems,
    /// Collection contains duplicate items
    UniqueItems,
    /// Invalid credit card number (Luhn check failed)
    CreditCard,
}

impl ValidationError {
    /// Create a new empty validation error container.
    pub fn new() -> Self {
        Self { errors: Vec::new() }
    }

    /// Check if there are any validation errors.
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// Add a field validation error.
    pub fn add(
        &mut self,
        field: impl Into<String>,
        kind: ValidationErrorKind,
        message: impl Into<String>,
    ) {
        self.errors.push(FieldValidationError {
            field: field.into(),
            kind,
            message: message.into(),
        });
    }

    /// Add a min value error.
    pub fn add_min(
        &mut self,
        field: impl Into<String>,
        min: impl std::fmt::Display,
        actual: impl std::fmt::Display,
    ) {
        self.add(
            field,
            ValidationErrorKind::Min,
            format!("must be at least {min}, got {actual}"),
        );
    }

    /// Add a max value error.
    pub fn add_max(
        &mut self,
        field: impl Into<String>,
        max: impl std::fmt::Display,
        actual: impl std::fmt::Display,
    ) {
        self.add(
            field,
            ValidationErrorKind::Max,
            format!("must be at most {max}, got {actual}"),
        );
    }

    /// Add a multiple_of error.
    ///
    /// Used when a numeric value is not a multiple of the specified divisor.
    pub fn add_multiple_of(
        &mut self,
        field: impl Into<String>,
        divisor: impl std::fmt::Display,
        actual: impl std::fmt::Display,
    ) {
        self.add(
            field,
            ValidationErrorKind::MultipleOf,
            format!("must be a multiple of {divisor}, got {actual}"),
        );
    }

    /// Add a min_items error for collections.
    ///
    /// Used when a collection has fewer items than the minimum required.
    pub fn add_min_items(&mut self, field: impl Into<String>, min: usize, actual: usize) {
        self.add(
            field,
            ValidationErrorKind::MinItems,
            format!("must have at least {min} items, got {actual}"),
        );
    }

    /// Add a max_items error for collections.
    ///
    /// Used when a collection has more items than the maximum allowed.
    pub fn add_max_items(&mut self, field: impl Into<String>, max: usize, actual: usize) {
        self.add(
            field,
            ValidationErrorKind::MaxItems,
            format!("must have at most {max} items, got {actual}"),
        );
    }

    /// Add a unique_items error for collections.
    ///
    /// Used when a collection contains duplicate items.
    pub fn add_unique_items(&mut self, field: impl Into<String>, duplicate_count: usize) {
        self.add(
            field,
            ValidationErrorKind::UniqueItems,
            format!("must have unique items, found {duplicate_count} duplicate(s)"),
        );
    }

    /// Add a min length error.
    pub fn add_min_length(&mut self, field: impl Into<String>, min: usize, actual: usize) {
        self.add(
            field,
            ValidationErrorKind::MinLength,
            format!("must be at least {min} characters, got {actual}"),
        );
    }

    /// Add a max length error.
    pub fn add_max_length(&mut self, field: impl Into<String>, max: usize, actual: usize) {
        self.add(
            field,
            ValidationErrorKind::MaxLength,
            format!("must be at most {max} characters, got {actual}"),
        );
    }

    /// Add a pattern match error.
    pub fn add_pattern(&mut self, field: impl Into<String>, pattern: &str) {
        self.add(
            field,
            ValidationErrorKind::Pattern,
            format!("must match pattern '{pattern}'"),
        );
    }

    /// Add a required field error.
    pub fn add_required(&mut self, field: impl Into<String>) {
        self.add(
            field,
            ValidationErrorKind::Required,
            "is required".to_string(),
        );
    }

    /// Add a custom validation error.
    pub fn add_custom(&mut self, field: impl Into<String>, message: impl Into<String>) {
        self.add(field, ValidationErrorKind::Custom, message);
    }

    /// Add a model-level validation error.
    ///
    /// Model-level validators check cross-field constraints or validate the
    /// entire model state. The error is recorded with field "__model__".
    pub fn add_model_error(&mut self, message: impl Into<String>) {
        self.add("__model__", ValidationErrorKind::Model, message);
    }

    /// Add a credit card validation error.
    pub fn add_credit_card(&mut self, field: impl Into<String>) {
        self.add(
            field,
            ValidationErrorKind::CreditCard,
            "is not a valid credit card number".to_string(),
        );
    }

    /// Convert to Result, returning Ok(()) if no errors, Err(self) otherwise.
    pub fn into_result(self) -> std::result::Result<(), Self> {
        if self.is_empty() { Ok(()) } else { Err(self) }
    }
}

impl Default for ValidationError {
    fn default() -> Self {
        Self::new()
    }
}

impl Error {
    /// Is this a retryable error (deadlock, serialization, pool exhausted, timeouts)?
    pub fn is_retryable(&self) -> bool {
        match self {
            Error::Query(q) => matches!(
                q.kind,
                QueryErrorKind::Deadlock | QueryErrorKind::Serialization | QueryErrorKind::Timeout
            ),
            Error::Pool(p) => matches!(p.kind, PoolErrorKind::Exhausted | PoolErrorKind::Timeout),
            Error::Connection(c) => matches!(c.kind, ConnectionErrorKind::PoolExhausted),
            Error::Timeout => true,
            _ => false,
        }
    }

    /// Is this error due to a poisoned mutex in the connection pool?
    ///
    /// A poisoned mutex indicates a thread panicked while holding the lock.
    /// This is a serious internal error and the pool may be in an inconsistent state.
    pub fn is_pool_poisoned(&self) -> bool {
        matches!(self, Error::Pool(p) if p.kind == PoolErrorKind::Poisoned)
    }

    /// Is this a connection error that likely requires reconnection?
    pub fn is_connection_error(&self) -> bool {
        match self {
            Error::Connection(c) => matches!(
                c.kind,
                ConnectionErrorKind::Connect
                    | ConnectionErrorKind::Authentication
                    | ConnectionErrorKind::Disconnected
                    | ConnectionErrorKind::Ssl
                    | ConnectionErrorKind::DnsResolution
                    | ConnectionErrorKind::Refused
            ),
            Error::Protocol(_) | Error::Io(_) => true,
            _ => false,
        }
    }

    /// Get SQLSTATE if available (e.g., "23505" for unique violation)
    pub fn sqlstate(&self) -> Option<&str> {
        match self {
            Error::Query(q) => q.sqlstate.as_deref(),
            _ => None,
        }
    }

    /// Get the SQL that caused this error, if available
    pub fn sql(&self) -> Option<&str> {
        match self {
            Error::Query(q) => q.sql.as_deref(),
            _ => None,
        }
    }
}

impl QueryError {
    /// Is this a unique constraint violation?
    pub fn is_unique_violation(&self) -> bool {
        self.sqlstate.as_deref() == Some("23505")
    }

    /// Is this a foreign key violation?
    pub fn is_foreign_key_violation(&self) -> bool {
        self.sqlstate.as_deref() == Some("23503")
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Connection(e) => write!(f, "Connection error: {}", e.message),
            Error::Query(e) => {
                if let Some(sqlstate) = &e.sqlstate {
                    write!(f, "Query error (SQLSTATE {}): {}", sqlstate, e.message)
                } else {
                    write!(f, "Query error: {}", e.message)
                }
            }
            Error::Type(e) => {
                if let Some(col) = &e.column {
                    write!(
                        f,
                        "Type error in column '{}': expected {}, found {}",
                        col, e.expected, e.actual
                    )
                } else {
                    write!(f, "Type error: expected {}, found {}", e.expected, e.actual)
                }
            }
            Error::Transaction(e) => write!(f, "Transaction error: {}", e.message),
            Error::Protocol(e) => write!(f, "Protocol error: {}", e.message),
            Error::Pool(e) => write!(f, "Pool error: {}", e.message),
            Error::Schema(e) => write!(f, "Schema error: {}", e.message),
            Error::Config(e) => write!(f, "Configuration error: {}", e.message),
            Error::Validation(e) => write!(f, "Validation error: {}", e),
            Error::Io(e) => write!(f, "I/O error: {}", e),
            Error::Timeout => write!(f, "Operation timed out"),
            Error::Cancelled => write!(f, "Operation cancelled"),
            Error::Serde(msg) => write!(f, "Serialization error: {}", msg),
            Error::Custom(msg) => write!(f, "{}", msg),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Connection(e) => e
                .source
                .as_deref()
                .map(|err| err as &(dyn std::error::Error + 'static)),
            Error::Query(e) => e
                .source
                .as_deref()
                .map(|err| err as &(dyn std::error::Error + 'static)),
            Error::Protocol(e) => e
                .source
                .as_deref()
                .map(|err| err as &(dyn std::error::Error + 'static)),
            Error::Pool(e) => e
                .source
                .as_deref()
                .map(|err| err as &(dyn std::error::Error + 'static)),
            Error::Schema(e) => e
                .source
                .as_deref()
                .map(|err| err as &(dyn std::error::Error + 'static)),
            Error::Config(e) => e
                .source
                .as_deref()
                .map(|err| err as &(dyn std::error::Error + 'static)),
            Error::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl fmt::Display for ConnectionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl fmt::Display for QueryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(sqlstate) = &self.sqlstate {
            write!(f, "{} (SQLSTATE {})", self.message, sqlstate)
        } else {
            write!(f, "{}", self.message)
        }
    }
}

impl fmt::Display for TypeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(col) = &self.column {
            write!(
                f,
                "expected {} for column '{}', found {}",
                self.expected, col, self.actual
            )
        } else {
            write!(f, "expected {}, found {}", self.expected, self.actual)
        }
    }
}

impl fmt::Display for TransactionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl fmt::Display for ProtocolError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl fmt::Display for PoolError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl fmt::Display for SchemaError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.errors.is_empty() {
            write!(f, "validation passed")
        } else if self.errors.len() == 1 {
            let err = &self.errors[0];
            write!(f, "validation error on '{}': {}", err.field, err.message)
        } else {
            writeln!(f, "validation errors:")?;
            for err in &self.errors {
                writeln!(f, "  - {}: {}", err.field, err.message)?;
            }
            Ok(())
        }
    }
}

impl std::error::Error for ValidationError {}

impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Self {
        Error::Io(err)
    }
}

impl From<ConnectionError> for Error {
    fn from(err: ConnectionError) -> Self {
        Error::Connection(err)
    }
}

impl From<QueryError> for Error {
    fn from(err: QueryError) -> Self {
        Error::Query(err)
    }
}

impl From<TypeError> for Error {
    fn from(err: TypeError) -> Self {
        Error::Type(err)
    }
}

impl From<TransactionError> for Error {
    fn from(err: TransactionError) -> Self {
        Error::Transaction(err)
    }
}

impl From<ProtocolError> for Error {
    fn from(err: ProtocolError) -> Self {
        Error::Protocol(err)
    }
}

impl From<PoolError> for Error {
    fn from(err: PoolError) -> Self {
        Error::Pool(err)
    }
}

impl From<SchemaError> for Error {
    fn from(err: SchemaError) -> Self {
        Error::Schema(err)
    }
}

impl From<ConfigError> for Error {
    fn from(err: ConfigError) -> Self {
        Error::Config(err)
    }
}

impl From<ValidationError> for Error {
    fn from(err: ValidationError) -> Self {
        Error::Validation(err)
    }
}

/// Result type alias for SQLModel operations.
pub type Result<T> = std::result::Result<T, Error>;

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

    #[test]
    fn sqlstate_helpers() {
        let query = QueryError {
            kind: QueryErrorKind::Constraint,
            sql: Some("SELECT 1".to_string()),
            sqlstate: Some("23505".to_string()),
            message: "unique violation".to_string(),
            detail: None,
            hint: None,
            position: None,
            source: None,
        };

        assert!(query.is_unique_violation());
        assert!(!query.is_foreign_key_violation());

        let err = Error::Query(query);
        assert_eq!(err.sqlstate(), Some("23505"));
        assert_eq!(err.sql(), Some("SELECT 1"));
    }

    #[test]
    fn retryable_and_connection_flags() {
        let retryable_query = Error::Query(QueryError {
            kind: QueryErrorKind::Deadlock,
            sql: None,
            sqlstate: None,
            message: "deadlock detected".to_string(),
            detail: None,
            hint: None,
            position: None,
            source: None,
        });

        let pool_exhausted = Error::Pool(PoolError {
            kind: PoolErrorKind::Exhausted,
            message: "pool exhausted".to_string(),
            source: None,
        });

        let conn_exhausted = Error::Connection(ConnectionError {
            kind: ConnectionErrorKind::PoolExhausted,
            message: "pool exhausted".to_string(),
            source: None,
        });

        assert!(retryable_query.is_retryable());
        assert!(pool_exhausted.is_retryable());
        assert!(conn_exhausted.is_retryable());

        let conn_error = Error::Connection(ConnectionError {
            kind: ConnectionErrorKind::Disconnected,
            message: "lost connection".to_string(),
            source: None,
        });
        assert!(conn_error.is_connection_error());
    }

    #[test]
    fn pool_poisoned_error() {
        // Test the convenience constructor
        let err = PoolError::poisoned("acquire");
        assert_eq!(err.kind, PoolErrorKind::Poisoned);
        assert!(err.message.contains("acquire"));
        assert!(err.message.contains("poisoned"));
        assert!(err.message.contains("panicked"));

        // Test wrapped in Error
        let error = Error::Pool(err);
        assert!(error.is_pool_poisoned());
        assert!(!error.is_retryable()); // Poisoned errors are NOT retryable
        assert!(!error.is_connection_error());

        // Test Display
        let display = format!("{}", error);
        assert!(display.contains("Pool error"));
        assert!(display.contains("poisoned"));
    }

    #[test]
    fn pool_poisoned_not_retryable() {
        let poisoned = Error::Pool(PoolError::poisoned("close"));
        let exhausted = Error::Pool(PoolError {
            kind: PoolErrorKind::Exhausted,
            message: "no connections".to_string(),
            source: None,
        });
        let timeout = Error::Pool(PoolError {
            kind: PoolErrorKind::Timeout,
            message: "timed out".to_string(),
            source: None,
        });

        // Poisoned is NOT retryable (it's a permanent failure)
        assert!(!poisoned.is_retryable());
        // But exhausted and timeout ARE retryable
        assert!(exhausted.is_retryable());
        assert!(timeout.is_retryable());
    }
}