exarrow-rs 0.29.0

ADBC-compatible driver for Exasol with Arrow data format support
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
//! Error types for exarrow-rs.
//!
//! This module defines domain-specific error types organized by functional area.

use thiserror::Error;

/// Top-level error type encompassing all possible errors.
#[derive(Error, Debug)]
pub enum ExasolError {
    /// Connection-related errors
    #[error(transparent)]
    Connection(#[from] ConnectionError),

    /// Query execution errors
    #[error(transparent)]
    Query(#[from] QueryError),

    /// Data conversion errors
    #[error(transparent)]
    Conversion(#[from] ConversionError),

    /// Transport protocol errors
    #[error(transparent)]
    Transport(#[from] TransportError),
}

/// Errors related to database connections.
#[derive(Error, Debug)]
pub enum ConnectionError {
    /// Failed to establish connection to the database
    #[error("Failed to connect to {host}:{port}: {message}")]
    ConnectionFailed {
        host: String,
        port: u16,
        message: String,
    },

    /// Authentication failure
    #[error("Authentication failed: {0}")]
    AuthenticationFailed(String),

    /// Invalid connection parameters
    #[error("Invalid connection parameter '{parameter}': {message}")]
    InvalidParameter { parameter: String, message: String },

    /// Connection string parsing error
    #[error("Failed to parse connection string: {0}")]
    ParseError(String),

    /// Connection timeout
    #[error("Connection timeout after {timeout_ms}ms")]
    Timeout { timeout_ms: u64 },

    /// Connection is closed
    #[error("Connection is closed")]
    ConnectionClosed,

    /// TLS/SSL error
    #[error("TLS error: {0}")]
    TlsError(String),
}

/// Errors related to query execution.
#[derive(Error, Debug)]
pub enum QueryError {
    /// SQL syntax error
    #[error("SQL syntax error at position {position}: {message}")]
    SyntaxError { position: usize, message: String },

    /// Query execution failed
    #[error("Query execution failed: {0}")]
    ExecutionFailed(String),

    /// Query timeout
    #[error("Query timeout after {timeout_ms}ms")]
    Timeout { timeout_ms: u64 },

    /// Invalid query state
    #[error("Invalid query state: {0}")]
    InvalidState(String),

    /// Parameter binding error
    #[error("Parameter binding error for parameter {index}: {message}")]
    ParameterBindingError { index: usize, message: String },

    /// Result set not available
    #[error("Result set not available: {0}")]
    NoResultSet(String),

    /// Transaction error
    #[error("Transaction error: {0}")]
    TransactionError(String),

    /// SQL injection attempt detected
    #[error("Potential SQL injection detected")]
    SqlInjectionDetected,

    /// Prepared statement has been closed
    #[error("Prepared statement has been closed")]
    StatementClosed,

    /// Unexpected result set when row count was expected
    #[error("Expected row count but received result set")]
    UnexpectedResultSet,
}

/// Errors related to data type conversion.
#[derive(Error, Debug)]
pub enum ConversionError {
    /// Unsupported Exasol type
    #[error("Unsupported Exasol type: {exasol_type}")]
    UnsupportedType { exasol_type: String },

    /// Failed to convert value
    #[error("Failed to convert value at row {row}, column {column} ({column_name}) to {target_type}: {message}; value: {value}")]
    ValueConversionFailed {
        row: usize,
        column: usize,
        /// Column name from the result schema
        column_name: String,
        /// The JSON value that failed to convert, as JSON text
        value: String,
        /// Display text of the Arrow data type of the column
        target_type: String,
        message: String,
    },

    /// Schema mismatch
    #[error("Schema mismatch: {0}")]
    SchemaMismatch(String),

    /// Invalid data format
    #[error("Invalid data format: {0}")]
    InvalidFormat(String),

    /// Overflow during conversion
    #[error("Numeric overflow at row {row}, column {column} ({column_name}) for {target_type}: {message}; value: {value}")]
    NumericOverflow {
        row: usize,
        column: usize,
        /// Column name from the result schema
        column_name: String,
        /// The JSON value that overflowed, as JSON text
        value: String,
        /// Display text of the Arrow data type of the column
        target_type: String,
        /// Why the value does not fit the target type
        message: String,
    },

    /// Invalid UTF-8 string
    #[error("Invalid UTF-8 string at row {row}, column {column}")]
    InvalidUtf8 { row: usize, column: usize },

    /// Arrow error
    #[error("Arrow error: {0}")]
    ArrowError(String),
}

/// Failure of one per-value step while a JSON column becomes an Arrow array.
///
/// A per-value step knows the row and the reason but not the column, so the
/// per-column step adds the column context through `into_conversion_error`,
/// the only place that builds `ValueConversionFailed` and `NumericOverflow`.
#[derive(Debug)]
pub(crate) enum ColumnConversionError {
    Value {
        row: usize,
        reason: String,
        overflow: bool,
    },
    /// A column-level failure, such as an Arrow error, that needs no value context.
    Other(ConversionError),
}

impl ColumnConversionError {
    pub(crate) fn invalid_value(row: usize, reason: impl Into<String>) -> Self {
        Self::Value {
            row,
            reason: reason.into(),
            overflow: false,
        }
    }

    pub(crate) fn overflow(row: usize, reason: impl Into<String>) -> Self {
        Self::Value {
            row,
            reason: reason.into(),
            overflow: true,
        }
    }

    /// Attach the column index, name, failing value, and Arrow data type.
    ///
    /// `values` is the column's JSON values, indexed by row.
    pub(crate) fn into_conversion_error(
        self,
        column: usize,
        column_name: &str,
        values: &[&serde_json::Value],
        target_type: &arrow::datatypes::DataType,
    ) -> ConversionError {
        match self {
            Self::Other(error) => error,
            Self::Value {
                row,
                reason,
                overflow,
            } => {
                let value = values
                    .get(row)
                    .map_or(serde_json::Value::Null, |v| (*v).clone())
                    .to_string();
                let column_name = column_name.to_string();
                let target_type = target_type.to_string();
                if overflow {
                    ConversionError::NumericOverflow {
                        row,
                        column,
                        column_name,
                        value,
                        target_type,
                        message: reason,
                    }
                } else {
                    ConversionError::ValueConversionFailed {
                        row,
                        column,
                        column_name,
                        value,
                        target_type,
                        message: reason,
                    }
                }
            }
        }
    }
}

impl From<ConversionError> for ColumnConversionError {
    fn from(error: ConversionError) -> Self {
        Self::Other(error)
    }
}

/// Errors related to transport protocol.
#[derive(Error, Debug)]
pub enum TransportError {
    /// WebSocket connection error
    #[error("WebSocket error: {0}")]
    WebSocketError(String),

    /// Message serialization error
    #[error("Serialization error: {0}")]
    SerializationError(String),

    /// Message deserialization error
    #[error("Deserialization error: {0}")]
    DeserializationError(String),

    /// Protocol error
    #[error("Protocol error: {0}")]
    ProtocolError(String),

    /// Invalid response from server
    #[error("Invalid server response: {0}")]
    InvalidResponse(String),

    /// Network I/O error
    #[error("Network I/O error: {0}")]
    IoError(String),

    /// Message send error
    #[error("Failed to send message: {0}")]
    SendError(String),

    /// Message receive error
    #[error("Failed to receive message: {0}")]
    ReceiveError(String),

    /// TLS/SSL error
    #[error("TLS error: {0}")]
    TlsError(String),
}

// Conversions from external error types
impl From<arrow::error::ArrowError> for ConversionError {
    fn from(err: arrow::error::ArrowError) -> Self {
        ConversionError::ArrowError(err.to_string())
    }
}

impl From<serde_json::Error> for TransportError {
    fn from(err: serde_json::Error) -> Self {
        TransportError::SerializationError(err.to_string())
    }
}

#[cfg(feature = "websocket")]
impl From<tokio_tungstenite::tungstenite::Error> for TransportError {
    fn from(err: tokio_tungstenite::tungstenite::Error) -> Self {
        TransportError::WebSocketError(err.to_string())
    }
}

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

    #[test]
    fn test_connection_error_display() {
        let err = ConnectionError::ConnectionFailed {
            host: "localhost".to_string(),
            port: 8563,
            message: "Connection refused".to_string(),
        };
        assert!(err.to_string().contains("localhost"));
        assert!(err.to_string().contains("8563"));
    }

    #[test]
    fn test_query_error_display() {
        let err = QueryError::SyntaxError {
            position: 10,
            message: "Unexpected token".to_string(),
        };
        assert!(err.to_string().contains("position 10"));
    }

    #[test]
    fn test_conversion_error_display() {
        let err = ConversionError::ValueConversionFailed {
            row: 5,
            column: 2,
            column_name: "PRICE".to_string(),
            value: "\"abc\"".to_string(),
            target_type: "Float64".to_string(),
            message: "Invalid number format".to_string(),
        };
        assert!(err.to_string().contains("row 5"));
        assert!(err.to_string().contains("column 2"));
    }

    #[test]
    fn column_context_turns_a_value_failure_into_value_conversion_failed() {
        let values = [&serde_json::Value::Null, &serde_json::json!("yes")];
        let err = ColumnConversionError::invalid_value(1, "Expected boolean")
            .into_conversion_error(3, "FLAG", &values, &arrow::datatypes::DataType::Boolean);
        match err {
            ConversionError::ValueConversionFailed {
                row,
                column,
                column_name,
                value,
                target_type,
                message,
            } => {
                assert_eq!(
                    (row, column, column_name.as_str(), message.as_str()),
                    (1, 3, "FLAG", "Expected boolean")
                );
                assert_eq!(value, "\"yes\"");
                assert_eq!(target_type, "Boolean");
            }
            other => panic!("expected ValueConversionFailed, got {other:?}"),
        }
    }

    #[test]
    fn column_context_turns_an_overflow_into_numeric_overflow() {
        let values = [&serde_json::json!("123456")];
        let err = ColumnConversionError::overflow(0, "too many digits").into_conversion_error(
            0,
            "AMOUNT",
            &values,
            &arrow::datatypes::DataType::Decimal128(5, 2),
        );
        assert!(matches!(
            err,
            ConversionError::NumericOverflow { row: 0, column: 0, ref column_name, ref value, ref target_type, ref message }
                if column_name == "AMOUNT" && value == "\"123456\"" && target_type == "Decimal128(5, 2)"
                    && message == "too many digits"
        ));
    }

    #[test]
    fn column_context_returns_a_carried_conversion_error_unchanged() {
        let err = ColumnConversionError::from(ConversionError::ArrowError("bad precision".into()))
            .into_conversion_error(0, "X", &[], &arrow::datatypes::DataType::Boolean);
        assert_eq!(err.to_string(), "Arrow error: bad precision");
    }

    #[test]
    fn test_transport_tls_error() {
        let err = TransportError::TlsError("Certificate validation failed".to_string());
        assert!(err.to_string().contains("TLS error"));
        assert!(err.to_string().contains("Certificate validation failed"));
    }

    #[test]
    fn test_statement_closed_error() {
        let err = QueryError::StatementClosed;
        assert!(err.to_string().contains("closed"));
    }

    #[test]
    fn test_unexpected_result_set_error() {
        let err = QueryError::UnexpectedResultSet;
        assert!(err.to_string().contains("result set"));
    }

    // =========================================================================
    // Conversions from external error types
    // =========================================================================

    #[test]
    fn test_conversion_error_from_arrow_error_keeps_the_arrow_message() {
        let arrow_error = arrow::error::ArrowError::InvalidArgumentError("bad column".to_string());
        let arrow_message = arrow_error.to_string();

        let err: ConversionError = arrow_error.into();

        assert!(matches!(err, ConversionError::ArrowError(_)));
        assert_eq!(err.to_string(), format!("Arrow error: {}", arrow_message));
    }

    #[test]
    fn test_transport_error_from_serde_json_error_keeps_the_parser_message() {
        let json_error = serde_json::from_str::<serde_json::Value>("{not json").unwrap_err();
        let json_message = json_error.to_string();

        let err: TransportError = json_error.into();

        assert!(matches!(err, TransportError::SerializationError(_)));
        assert_eq!(
            err.to_string(),
            format!("Serialization error: {}", json_message)
        );
    }

    // =========================================================================
    // ExasolError wraps each domain error transparently
    // =========================================================================

    #[test]
    fn test_exasol_error_from_connection_error_is_transparent() {
        let err: ExasolError = ConnectionError::ConnectionClosed.into();

        assert!(matches!(err, ExasolError::Connection(_)));
        assert_eq!(err.to_string(), "Connection is closed");
    }

    #[test]
    fn test_exasol_error_from_query_error_is_transparent() {
        let err: ExasolError = QueryError::StatementClosed.into();

        assert!(matches!(err, ExasolError::Query(_)));
        assert_eq!(err.to_string(), "Prepared statement has been closed");
    }

    #[test]
    fn test_exasol_error_from_conversion_error_is_transparent() {
        let err: ExasolError = ConversionError::SchemaMismatch("two columns".to_string()).into();

        assert!(matches!(err, ExasolError::Conversion(_)));
        assert_eq!(err.to_string(), "Schema mismatch: two columns");
    }

    #[test]
    fn test_exasol_error_from_transport_error_is_transparent() {
        let err: ExasolError = TransportError::ProtocolError("bad frame".to_string()).into();

        assert!(matches!(err, ExasolError::Transport(_)));
        assert_eq!(err.to_string(), "Protocol error: bad frame");
    }

    // =========================================================================
    // Every variant renders the context a caller needs to act on
    // =========================================================================

    #[test]
    fn test_every_connection_error_variant_renders_its_context() {
        let cases: Vec<(ConnectionError, &str)> = vec![
            (
                ConnectionError::ConnectionFailed {
                    host: "db.example".to_string(),
                    port: 8563,
                    message: "refused".to_string(),
                },
                "Failed to connect to db.example:8563: refused",
            ),
            (
                ConnectionError::AuthenticationFailed("wrong user".to_string()),
                "Authentication failed: wrong user",
            ),
            (
                ConnectionError::InvalidParameter {
                    parameter: "port".to_string(),
                    message: "not a number".to_string(),
                },
                "Invalid connection parameter 'port': not a number",
            ),
            (
                ConnectionError::ParseError("missing host".to_string()),
                "Failed to parse connection string: missing host",
            ),
            (
                ConnectionError::Timeout { timeout_ms: 2500 },
                "Connection timeout after 2500ms",
            ),
            (ConnectionError::ConnectionClosed, "Connection is closed"),
            (
                ConnectionError::TlsError("untrusted certificate".to_string()),
                "TLS error: untrusted certificate",
            ),
        ];

        for (err, expected) in cases {
            assert_eq!(err.to_string(), expected);
        }
    }

    #[test]
    fn test_every_query_error_variant_renders_its_context() {
        let cases: Vec<(QueryError, &str)> = vec![
            (
                QueryError::SyntaxError {
                    position: 7,
                    message: "unexpected FROM".to_string(),
                },
                "SQL syntax error at position 7: unexpected FROM",
            ),
            (
                QueryError::ExecutionFailed("table missing".to_string()),
                "Query execution failed: table missing",
            ),
            (
                QueryError::Timeout { timeout_ms: 30_000 },
                "Query timeout after 30000ms",
            ),
            (
                QueryError::InvalidState("not prepared".to_string()),
                "Invalid query state: not prepared",
            ),
            (
                QueryError::ParameterBindingError {
                    index: 2,
                    message: "NaN".to_string(),
                },
                "Parameter binding error for parameter 2: NaN",
            ),
            (
                QueryError::NoResultSet("row count only".to_string()),
                "Result set not available: row count only",
            ),
            (
                QueryError::TransactionError("rollback failed".to_string()),
                "Transaction error: rollback failed",
            ),
            (
                QueryError::SqlInjectionDetected,
                "Potential SQL injection detected",
            ),
            (
                QueryError::StatementClosed,
                "Prepared statement has been closed",
            ),
            (
                QueryError::UnexpectedResultSet,
                "Expected row count but received result set",
            ),
        ];

        for (err, expected) in cases {
            assert_eq!(err.to_string(), expected);
        }
    }

    #[test]
    fn test_every_conversion_error_variant_renders_its_context() {
        let cases: Vec<(ConversionError, &str)> = vec![
            (
                ConversionError::UnsupportedType {
                    exasol_type: "XML".to_string(),
                },
                "Unsupported Exasol type: XML",
            ),
            (
                ConversionError::ValueConversionFailed {
                    row: 3,
                    column: 4,
                    column_name: "QTY".to_string(),
                    value: "\"x\"".to_string(),
                    target_type: "Int64".to_string(),
                    message: "not a number".to_string(),
                },
                "Failed to convert value at row 3, column 4 (QTY) to Int64: not a number; value: \"x\"",
            ),
            (
                ConversionError::SchemaMismatch("column count".to_string()),
                "Schema mismatch: column count",
            ),
            (
                ConversionError::InvalidFormat("Empty decimal string".to_string()),
                "Invalid data format: Empty decimal string",
            ),
            (
                ConversionError::NumericOverflow {
                    row: 1,
                    column: 2,
                    column_name: "AMOUNT".to_string(),
                    value: "\"123456\"".to_string(),
                    target_type: "Decimal128(5, 2)".to_string(),
                    message: "6 significant digits exceed precision 5".to_string(),
                },
                "Numeric overflow at row 1, column 2 (AMOUNT) for Decimal128(5, 2): 6 significant digits exceed precision 5; value: \"123456\"",
            ),
            (
                ConversionError::InvalidUtf8 { row: 5, column: 6 },
                "Invalid UTF-8 string at row 5, column 6",
            ),
            (
                ConversionError::ArrowError("length mismatch".to_string()),
                "Arrow error: length mismatch",
            ),
        ];

        for (err, expected) in cases {
            assert_eq!(err.to_string(), expected);
        }
    }

    #[test]
    fn test_every_transport_error_variant_renders_its_context() {
        let cases: Vec<(TransportError, &str)> = vec![
            (
                TransportError::WebSocketError("handshake".to_string()),
                "WebSocket error: handshake",
            ),
            (
                TransportError::SerializationError("bad value".to_string()),
                "Serialization error: bad value",
            ),
            (
                TransportError::DeserializationError("bad frame".to_string()),
                "Deserialization error: bad frame",
            ),
            (
                TransportError::ProtocolError("unexpected state".to_string()),
                "Protocol error: unexpected state",
            ),
            (
                TransportError::InvalidResponse("no status".to_string()),
                "Invalid server response: no status",
            ),
            (
                TransportError::IoError("broken pipe".to_string()),
                "Network I/O error: broken pipe",
            ),
            (
                TransportError::SendError("closed".to_string()),
                "Failed to send message: closed",
            ),
            (
                TransportError::ReceiveError("timeout".to_string()),
                "Failed to receive message: timeout",
            ),
            (
                TransportError::TlsError("unknown ca".to_string()),
                "TLS error: unknown ca",
            ),
        ];

        for (err, expected) in cases {
            assert_eq!(err.to_string(), expected);
        }
    }
}