toasty-core 0.2.0

Core types, schema representations, and driver interface for Toasty
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
//! Error types for Toasty operations.
//!
//! This module defines [`Error`], the unified error type used throughout
//! Toasty. Errors are cheap to clone (backed by `Arc`) and support chaining
//! via [`Error::context`]. Each error variant has a dedicated constructor
//! (e.g., [`Error::record_not_found`]) and a corresponding predicate
//! (e.g., [`Error::is_record_not_found`]).

mod adhoc;
mod condition_failed;
mod connection_pool;
mod driver_operation_failed;
mod expression_evaluation_failed;
mod invalid_connection_url;
mod invalid_driver_configuration;
mod invalid_record_count;
mod invalid_result;
mod invalid_schema;
mod invalid_statement;
mod invalid_type_conversion;
mod read_only_transaction;
mod record_not_found;
mod serialization_failure;
mod transaction_timeout;
mod unsupported_feature;
mod validation;

use adhoc::Adhoc;
use condition_failed::ConditionFailed;
use connection_pool::ConnectionPool;
use driver_operation_failed::DriverOperationFailed;
use expression_evaluation_failed::ExpressionEvaluationFailed;
use invalid_connection_url::InvalidConnectionUrl;
use invalid_driver_configuration::InvalidDriverConfiguration;
use invalid_record_count::InvalidRecordCount;
use invalid_result::InvalidResult;
use invalid_schema::InvalidSchema;
use invalid_statement::InvalidStatement;
use invalid_type_conversion::InvalidTypeConversion;
use read_only_transaction::ReadOnlyTransaction;
use record_not_found::RecordNotFound;
use serialization_failure::SerializationFailure;
use std::sync::Arc;
use transaction_timeout::TransactionTimeout;
use unsupported_feature::UnsupportedFeature;
use validation::ValidationFailed;

/// The error type used throughout Toasty.
///
/// `Error` is a thin wrapper around an `Arc`, making it cheap to clone. Errors
/// form a chain: each error can optionally carry a *cause* that provides
/// additional context.  When displayed, the chain is printed from outermost
/// context to innermost root cause, separated by `: `.
///
/// Construct errors through the associated functions on this type
/// (e.g., [`Error::record_not_found`], [`Error::from_args`]).
///
/// # Examples
///
/// ```
/// use toasty_core::Error;
///
/// // Create an ad-hoc error
/// let err = Error::from_args(format_args!("something went wrong"));
/// assert_eq!(err.to_string(), "something went wrong");
///
/// // Wrap it with additional context
/// let wrapped = err.context(Error::from_args(format_args!("while loading user")));
/// assert_eq!(wrapped.to_string(), "while loading user: something went wrong");
/// ```
#[derive(Clone)]
pub struct Error {
    inner: Arc<ErrorInner>,
}

/// Trait for types that can be converted into an [`Error`].
///
/// This is used by [`Error::context`] to accept either an `Error` directly or
/// any type that can be converted into one.
///
/// # Examples
///
/// ```
/// use toasty_core::Error;
///
/// // Error itself implements IntoError, so you can pass it directly:
/// let cause = Error::from_args(format_args!("root cause"));
/// let outer = Error::from_args(format_args!("outer"));
/// let chained = cause.context(outer);
/// assert_eq!(chained.to_string(), "outer: root cause");
/// ```
pub trait IntoError {
    /// Converts this type into an [`Error`].
    fn into_error(self) -> Error;
}

#[derive(Debug)]
struct ErrorInner {
    kind: ErrorKind,
    cause: Option<Error>,
}

#[derive(Debug)]
enum ErrorKind {
    Adhoc(Adhoc),
    DriverOperationFailed(DriverOperationFailed),
    ConnectionPool(ConnectionPool),
    ExpressionEvaluationFailed(ExpressionEvaluationFailed),
    InvalidConnectionUrl(InvalidConnectionUrl),
    InvalidDriverConfiguration(InvalidDriverConfiguration),
    InvalidTypeConversion(InvalidTypeConversion),
    InvalidRecordCount(InvalidRecordCount),
    RecordNotFound(RecordNotFound),
    InvalidResult(InvalidResult),
    InvalidSchema(InvalidSchema),
    InvalidStatement(InvalidStatement),
    ReadOnlyTransaction(ReadOnlyTransaction),
    SerializationFailure(SerializationFailure),
    TransactionTimeout(TransactionTimeout),
    UnsupportedFeature(UnsupportedFeature),
    ValidationFailed(ValidationFailed),
    ConditionFailed(ConditionFailed),
}

impl Error {
    /// Wraps this error with additional context.
    ///
    /// The `consequent` becomes the new outermost error and `self` becomes its
    /// cause. When displayed, the chain reads from outermost to innermost:
    ///
    /// ```text
    /// consequent: self
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `consequent` already has a cause attached.
    ///
    /// # Examples
    ///
    /// ```
    /// use toasty_core::Error;
    ///
    /// let root = Error::from_args(format_args!("disk full"));
    /// let err = root.context(Error::from_args(format_args!("failed to save")));
    /// assert_eq!(err.to_string(), "failed to save: disk full");
    /// ```
    pub fn context(self, consequent: impl IntoError) -> Error {
        self.context_impl(consequent.into_error())
    }

    fn context_impl(self, consequent: Error) -> Error {
        let mut err = consequent;
        let inner = Arc::get_mut(&mut err.inner).unwrap();
        assert!(
            inner.cause.is_none(),
            "consequent error must not already have a cause"
        );
        inner.cause = Some(self);
        err
    }

    fn chain(&self) -> impl Iterator<Item = &Error> {
        let mut err = self;
        core::iter::once(err).chain(core::iter::from_fn(move || {
            err = err.inner.cause.as_ref()?;
            Some(err)
        }))
    }

    fn kind(&self) -> &ErrorKind {
        &self.inner.kind
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self.kind() {
            ErrorKind::DriverOperationFailed(err) => Some(err),
            ErrorKind::ConnectionPool(err) => Some(err),
            _ => None,
        }
    }
}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        let mut it = self.chain().peekable();
        while let Some(err) = it.next() {
            core::fmt::Display::fmt(err.kind(), f)?;
            if it.peek().is_some() {
                f.write_str(": ")?;
            }
        }
        Ok(())
    }
}

impl core::fmt::Debug for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        if !f.alternate() {
            core::fmt::Display::fmt(self, f)
        } else {
            f.debug_struct("Error")
                .field("kind", &self.inner.kind)
                .field("cause", &self.inner.cause)
                .finish()
        }
    }
}

impl core::fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        use self::ErrorKind::*;

        match self {
            Adhoc(err) => core::fmt::Display::fmt(err, f),
            DriverOperationFailed(err) => core::fmt::Display::fmt(err, f),
            ConnectionPool(err) => core::fmt::Display::fmt(err, f),
            ExpressionEvaluationFailed(err) => core::fmt::Display::fmt(err, f),
            InvalidConnectionUrl(err) => core::fmt::Display::fmt(err, f),
            InvalidDriverConfiguration(err) => core::fmt::Display::fmt(err, f),
            InvalidTypeConversion(err) => core::fmt::Display::fmt(err, f),
            InvalidRecordCount(err) => core::fmt::Display::fmt(err, f),
            RecordNotFound(err) => core::fmt::Display::fmt(err, f),
            InvalidResult(err) => core::fmt::Display::fmt(err, f),
            InvalidSchema(err) => core::fmt::Display::fmt(err, f),
            InvalidStatement(err) => core::fmt::Display::fmt(err, f),
            ReadOnlyTransaction(err) => core::fmt::Display::fmt(err, f),
            SerializationFailure(err) => core::fmt::Display::fmt(err, f),
            TransactionTimeout(err) => core::fmt::Display::fmt(err, f),
            UnsupportedFeature(err) => core::fmt::Display::fmt(err, f),
            ValidationFailed(err) => core::fmt::Display::fmt(err, f),
            ConditionFailed(err) => core::fmt::Display::fmt(err, f),
        }
    }
}

impl From<ErrorKind> for Error {
    fn from(kind: ErrorKind) -> Error {
        Error {
            inner: Arc::new(ErrorInner { kind, cause: None }),
        }
    }
}

impl IntoError for Error {
    fn into_error(self) -> Error {
        self
    }
}

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

    #[test]
    fn error_size() {
        // Ensure Error stays at one word (size of pointer/Arc)
        let expected_size = core::mem::size_of::<usize>();
        assert_eq!(expected_size, core::mem::size_of::<Error>());
    }

    #[test]
    fn error_from_args() {
        let err = Error::from_args(format_args!("test error: {}", 42));
        assert_eq!(err.to_string(), "test error: 42");
    }

    #[test]
    fn error_chain_display() {
        let root = Error::from_args(format_args!("root cause"));
        let mid = Error::from_args(format_args!("middle context"));
        let top = Error::from_args(format_args!("top context"));

        let chained = root.context(mid).context(top);
        assert_eq!(
            chained.to_string(),
            "top context: middle context: root cause"
        );
    }

    #[test]
    fn type_conversion_error() {
        let value = crate::stmt::Value::I64(42);
        let err = Error::type_conversion(value, "String");
        assert_eq!(err.to_string(), "cannot convert I64 to String");
    }

    #[test]
    fn type_conversion_error_range() {
        // Simulates usize conversion failure due to range
        let value = crate::stmt::Value::U64(u64::MAX);
        let err = Error::type_conversion(value, "usize");
        assert_eq!(err.to_string(), "cannot convert U64 to usize");
    }

    #[test]
    fn record_not_found_with_immediate_context() {
        let err = Error::record_not_found("table=users key={id: 123}");
        assert_eq!(
            err.to_string(),
            "record not found: table=users key={id: 123}"
        );
    }

    #[test]
    fn record_not_found_with_context_chain() {
        let err = Error::record_not_found("table=users key={id: 123}")
            .context(Error::from_args(format_args!("update query failed")))
            .context(Error::from_args(format_args!("User.update() operation")));

        assert_eq!(
            err.to_string(),
            "User.update() operation: update query failed: record not found: table=users key={id: 123}"
        );
    }

    #[test]
    fn invalid_record_count_with_context() {
        let err = Error::invalid_record_count("expected 1 record, found multiple");
        assert_eq!(
            err.to_string(),
            "invalid record count: expected 1 record, found multiple"
        );
    }

    #[test]
    fn invalid_result_error() {
        let err = Error::invalid_result("expected Stream, got Count");
        assert_eq!(
            err.to_string(),
            "invalid result: expected Stream, got Count"
        );
    }

    #[test]
    fn validation_length_too_short() {
        let err = Error::validation_length(3, Some(5), Some(10));
        assert_eq!(err.to_string(), "value length 3 is too short (minimum: 5)");
    }

    #[test]
    fn validation_length_too_long() {
        let err = Error::validation_length(15, Some(5), Some(10));
        assert_eq!(err.to_string(), "value length 15 is too long (maximum: 10)");
    }

    #[test]
    fn validation_length_exact_mismatch() {
        let err = Error::validation_length(3, Some(5), Some(5));
        assert_eq!(
            err.to_string(),
            "value length 3 does not match required length 5"
        );
    }

    #[test]
    fn validation_length_min_only() {
        let err = Error::validation_length(3, Some(5), None);
        assert_eq!(err.to_string(), "value length 3 is too short (minimum: 5)");
    }

    #[test]
    fn validation_length_max_only() {
        let err = Error::validation_length(15, None, Some(10));
        assert_eq!(err.to_string(), "value length 15 is too long (maximum: 10)");
    }

    #[test]
    fn condition_failed_with_context() {
        let err = Error::condition_failed("optimistic lock version mismatch");
        assert_eq!(
            err.to_string(),
            "condition failed: optimistic lock version mismatch"
        );
    }

    #[test]
    fn condition_failed_with_format() {
        let expected = 1;
        let actual = 0;
        let err = Error::condition_failed(format!(
            "expected {} row affected, got {}",
            expected, actual
        ));
        assert_eq!(
            err.to_string(),
            "condition failed: expected 1 row affected, got 0"
        );
    }

    #[test]
    fn invalid_schema_error() {
        let err = Error::invalid_schema("duplicate index name `idx_users`");
        assert_eq!(
            err.to_string(),
            "invalid schema: duplicate index name `idx_users`"
        );
    }

    #[test]
    fn invalid_schema_with_context() {
        let err = Error::invalid_schema(
            "auto_increment column `id` in table `users` must have a numeric type, found String",
        )
        .context(Error::from_args(format_args!("schema verification failed")));
        assert_eq!(
            err.to_string(),
            "schema verification failed: invalid schema: auto_increment column `id` in table `users` must have a numeric type, found String"
        );
    }

    #[test]
    fn expression_evaluation_failed() {
        let err = Error::expression_evaluation_failed("failed to resolve argument");
        assert_eq!(
            err.to_string(),
            "expression evaluation failed: failed to resolve argument"
        );
    }

    #[test]
    fn expression_evaluation_failed_with_context() {
        let err = Error::expression_evaluation_failed("expected boolean value")
            .context(Error::from_args(format_args!("query execution failed")));
        assert_eq!(
            err.to_string(),
            "query execution failed: expression evaluation failed: expected boolean value"
        );
    }

    #[test]
    fn unsupported_feature() {
        let err = Error::unsupported_feature("VARCHAR type is not supported by this database");
        assert_eq!(
            err.to_string(),
            "unsupported feature: VARCHAR type is not supported by this database"
        );
    }

    #[test]
    fn unsupported_feature_with_context() {
        let err = Error::unsupported_feature("type List is not supported by this database")
            .context(Error::from_args(format_args!("schema creation failed")));
        assert_eq!(
            err.to_string(),
            "schema creation failed: unsupported feature: type List is not supported by this database"
        );
    }

    #[test]
    fn invalid_driver_configuration() {
        let err = Error::invalid_driver_configuration(
            "native_varchar is true but storage_types.varchar is None",
        );
        assert_eq!(
            err.to_string(),
            "invalid driver configuration: native_varchar is true but storage_types.varchar is None"
        );
    }

    #[test]
    fn invalid_driver_configuration_with_context() {
        let err = Error::invalid_driver_configuration("inconsistent capability flags").context(
            Error::from_args(format_args!("driver initialization failed")),
        );
        assert_eq!(
            err.to_string(),
            "driver initialization failed: invalid driver configuration: inconsistent capability flags"
        );
    }

    #[test]
    fn invalid_statement_error() {
        let err = Error::invalid_statement("field `unknown_field` does not exist on model `User`");
        assert_eq!(
            err.to_string(),
            "invalid statement: field `unknown_field` does not exist on model `User`"
        );
    }

    #[test]
    fn invalid_statement_with_context() {
        let err = Error::invalid_statement("cannot update primary key field `id`")
            .context(Error::from_args(format_args!("statement lowering failed")));
        assert_eq!(
            err.to_string(),
            "statement lowering failed: invalid statement: cannot update primary key field `id`"
        );
    }

    #[test]
    fn read_only_transaction_display() {
        let err = Error::read_only_transaction("cannot execute UPDATE in a read-only transaction");
        assert_eq!(
            err.to_string(),
            "read-only transaction: cannot execute UPDATE in a read-only transaction"
        );
    }

    #[test]
    fn read_only_transaction_is_predicate() {
        let err = Error::read_only_transaction("write not allowed");
        assert!(err.is_read_only_transaction());
    }

    #[test]
    fn read_only_transaction_predicate_false_for_other_errors() {
        let err = Error::serialization_failure("concurrent update conflict");
        assert!(!err.is_read_only_transaction());
    }

    #[test]
    fn read_only_transaction_with_context() {
        let err = Error::read_only_transaction("INSERT not allowed")
            .context(Error::from_args(format_args!("create user failed")));
        assert_eq!(
            err.to_string(),
            "create user failed: read-only transaction: INSERT not allowed"
        );
    }
}