Skip to main content

quack_rs/
error_data.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! Structured error data (`DuckDB` 1.5.0+).
7//!
8//! [`ErrorData`] is an RAII wrapper around `DuckDB`'s `duckdb_error_data` handle —
9//! the structured error type returned by several 1.5.0 C API surfaces, including
10//! expression folding ([`Expression::fold`][crate::expression::Expression::fold]),
11//! the file system API ([`crate::file_system`]), and the appender error accessor
12//! ([`Appender::error_data`][crate::appender::Appender::error_data]).
13//!
14//! Unlike a bare error string, an `ErrorData` carries both a human-readable
15//! message and a machine-readable [`DuckDbErrorType`] category, so an extension
16//! can branch on the kind of failure (e.g. distinguishing `IO` from
17//! `OutOfMemory`).
18//!
19//! # Example
20//!
21//! ```rust,no_run
22//! use quack_rs::error_data::{DuckDbErrorType, ErrorData};
23//!
24//! // Construct a structured error to hand back to DuckDB.
25//! let err = ErrorData::new(DuckDbErrorType::InvalidInput, "row index out of range");
26//! assert!(err.has_error());
27//! assert_eq!(err.error_type(), DuckDbErrorType::InvalidInput);
28//! ```
29
30use std::ffi::CStr;
31use std::fmt;
32
33use libduckdb_sys::{
34    duckdb_create_error_data, duckdb_destroy_error_data, duckdb_error_data,
35    duckdb_error_data_error_type, duckdb_error_data_has_error, duckdb_error_data_message,
36    duckdb_error_type, duckdb_error_type_DUCKDB_ERROR_BINDER,
37    duckdb_error_type_DUCKDB_ERROR_CATALOG, duckdb_error_type_DUCKDB_ERROR_CONNECTION,
38    duckdb_error_type_DUCKDB_ERROR_CONSTRAINT, duckdb_error_type_DUCKDB_ERROR_CONVERSION,
39    duckdb_error_type_DUCKDB_ERROR_DECIMAL, duckdb_error_type_DUCKDB_ERROR_DEPENDENCY,
40    duckdb_error_type_DUCKDB_ERROR_DIVIDE_BY_ZERO, duckdb_error_type_DUCKDB_ERROR_EXECUTOR,
41    duckdb_error_type_DUCKDB_ERROR_EXPRESSION, duckdb_error_type_DUCKDB_ERROR_FATAL,
42    duckdb_error_type_DUCKDB_ERROR_HTTP, duckdb_error_type_DUCKDB_ERROR_INDEX,
43    duckdb_error_type_DUCKDB_ERROR_INTERNAL, duckdb_error_type_DUCKDB_ERROR_INTERRUPT,
44    duckdb_error_type_DUCKDB_ERROR_INVALID, duckdb_error_type_DUCKDB_ERROR_INVALID_INPUT,
45    duckdb_error_type_DUCKDB_ERROR_INVALID_TYPE, duckdb_error_type_DUCKDB_ERROR_IO,
46    duckdb_error_type_DUCKDB_ERROR_MISMATCH_TYPE, duckdb_error_type_DUCKDB_ERROR_MISSING_EXTENSION,
47    duckdb_error_type_DUCKDB_ERROR_NETWORK, duckdb_error_type_DUCKDB_ERROR_NOT_IMPLEMENTED,
48    duckdb_error_type_DUCKDB_ERROR_NULL_POINTER, duckdb_error_type_DUCKDB_ERROR_OBJECT_SIZE,
49    duckdb_error_type_DUCKDB_ERROR_OPTIMIZER, duckdb_error_type_DUCKDB_ERROR_OUT_OF_MEMORY,
50    duckdb_error_type_DUCKDB_ERROR_OUT_OF_RANGE,
51    duckdb_error_type_DUCKDB_ERROR_PARAMETER_NOT_ALLOWED,
52    duckdb_error_type_DUCKDB_ERROR_PARAMETER_NOT_RESOLVED, duckdb_error_type_DUCKDB_ERROR_PARSER,
53    duckdb_error_type_DUCKDB_ERROR_PERMISSION, duckdb_error_type_DUCKDB_ERROR_PLANNER,
54    duckdb_error_type_DUCKDB_ERROR_SCHEDULER, duckdb_error_type_DUCKDB_ERROR_SERIALIZATION,
55    duckdb_error_type_DUCKDB_ERROR_SETTINGS, duckdb_error_type_DUCKDB_ERROR_STAT,
56    duckdb_error_type_DUCKDB_ERROR_SYNTAX, duckdb_error_type_DUCKDB_ERROR_TRANSACTION,
57    duckdb_error_type_DUCKDB_ERROR_UNKNOWN_TYPE, duckdb_valid_utf8_check, idx_t,
58};
59
60use crate::error::ExtensionError;
61
62/// The category of a `DuckDB` error, mirroring `duckdb_error_type`.
63///
64/// Unknown or future error categories map to [`DuckDbErrorType::Invalid`].
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66#[non_exhaustive]
67pub enum DuckDbErrorType {
68    /// No specific category / invalid.
69    Invalid,
70    /// Value out of the representable range.
71    OutOfRange,
72    /// A type conversion failed.
73    Conversion,
74    /// An unknown type was encountered.
75    UnknownType,
76    /// A decimal-specific error.
77    Decimal,
78    /// A type mismatch.
79    MismatchType,
80    /// Division by zero.
81    DivideByZero,
82    /// An object-size error.
83    ObjectSize,
84    /// An invalid type was supplied.
85    InvalidType,
86    /// A (de)serialization error.
87    Serialization,
88    /// A transaction error.
89    Transaction,
90    /// The requested feature is not implemented.
91    NotImplemented,
92    /// An error in an expression.
93    Expression,
94    /// A catalog error (e.g. missing table).
95    Catalog,
96    /// A parser error.
97    Parser,
98    /// A planner error.
99    Planner,
100    /// A scheduler error.
101    Scheduler,
102    /// An executor error.
103    Executor,
104    /// A constraint violation.
105    Constraint,
106    /// An index error.
107    Index,
108    /// A statistics error.
109    Stat,
110    /// A connection error.
111    Connection,
112    /// A syntax error.
113    Syntax,
114    /// A settings error.
115    Settings,
116    /// A binder error.
117    Binder,
118    /// A network error.
119    Network,
120    /// An optimizer error.
121    Optimizer,
122    /// A null-pointer error.
123    NullPointer,
124    /// An I/O error.
125    Io,
126    /// The query was interrupted.
127    Interrupt,
128    /// A fatal error — the database is in an unusable state.
129    Fatal,
130    /// An internal error (a `DuckDB` bug).
131    Internal,
132    /// Invalid input was supplied.
133    InvalidInput,
134    /// Out of memory.
135    OutOfMemory,
136    /// A permission error.
137    Permission,
138    /// A prepared-statement parameter could not be resolved.
139    ParameterNotResolved,
140    /// A prepared-statement parameter is not allowed here.
141    ParameterNotAllowed,
142    /// A dependency error.
143    Dependency,
144    /// An HTTP error.
145    Http,
146    /// A required extension is missing.
147    MissingExtension,
148    /// An extension could not be autoloaded (`DUCKDB_ERROR_AUTOLOAD`, 40).
149    Autoload,
150    /// A sequence error, e.g. `nextval` past the sequence's maximum
151    /// (`DUCKDB_ERROR_SEQUENCE`, 41).
152    Sequence,
153    /// An invalid database configuration
154    /// (`DUCKDB_INVALID_CONFIGURATION`, 42).
155    InvalidConfiguration,
156    /// Data corruption detected in persistent storage
157    /// (`DUCKDB_ERROR_DATA_CORRUPTION`, 43). Reported from `DuckDB` 2.0.0;
158    /// 1.x has no such category.
159    DataCorruption,
160    /// A resource is already in use (`DUCKDB_ERROR_RESOURCE_IN_USE`, 44):
161    /// from `DuckDB` 2.0.0, for one, a statement prepared or run on a
162    /// connection whose streaming result is still open. 1.x has no such
163    /// category.
164    ResourceInUse,
165}
166
167// `duckdb.h` (v1.5.5) numbers these 40, 41 and 42, and v2.0.0 adds 43 and
168// 44. They are spelled as literals rather than the `libduckdb_sys` constants
169// so the crate does not depend on which bindings version declares them; the
170// values are part of the stable C ABI.
171const DUCKDB_ERROR_AUTOLOAD: duckdb_error_type = 40;
172const DUCKDB_ERROR_SEQUENCE: duckdb_error_type = 41;
173const DUCKDB_INVALID_CONFIGURATION: duckdb_error_type = 42;
174const DUCKDB_ERROR_DATA_CORRUPTION: duckdb_error_type = 43;
175const DUCKDB_ERROR_RESOURCE_IN_USE: duckdb_error_type = 44;
176
177impl DuckDbErrorType {
178    /// Converts to the `DuckDB` C API constant.
179    #[must_use]
180    pub(crate) const fn to_raw(self) -> duckdb_error_type {
181        match self {
182            Self::Invalid => duckdb_error_type_DUCKDB_ERROR_INVALID,
183            Self::OutOfRange => duckdb_error_type_DUCKDB_ERROR_OUT_OF_RANGE,
184            Self::Conversion => duckdb_error_type_DUCKDB_ERROR_CONVERSION,
185            Self::UnknownType => duckdb_error_type_DUCKDB_ERROR_UNKNOWN_TYPE,
186            Self::Decimal => duckdb_error_type_DUCKDB_ERROR_DECIMAL,
187            Self::MismatchType => duckdb_error_type_DUCKDB_ERROR_MISMATCH_TYPE,
188            Self::DivideByZero => duckdb_error_type_DUCKDB_ERROR_DIVIDE_BY_ZERO,
189            Self::ObjectSize => duckdb_error_type_DUCKDB_ERROR_OBJECT_SIZE,
190            Self::InvalidType => duckdb_error_type_DUCKDB_ERROR_INVALID_TYPE,
191            Self::Serialization => duckdb_error_type_DUCKDB_ERROR_SERIALIZATION,
192            Self::Transaction => duckdb_error_type_DUCKDB_ERROR_TRANSACTION,
193            Self::NotImplemented => duckdb_error_type_DUCKDB_ERROR_NOT_IMPLEMENTED,
194            Self::Expression => duckdb_error_type_DUCKDB_ERROR_EXPRESSION,
195            Self::Catalog => duckdb_error_type_DUCKDB_ERROR_CATALOG,
196            Self::Parser => duckdb_error_type_DUCKDB_ERROR_PARSER,
197            Self::Planner => duckdb_error_type_DUCKDB_ERROR_PLANNER,
198            Self::Scheduler => duckdb_error_type_DUCKDB_ERROR_SCHEDULER,
199            Self::Executor => duckdb_error_type_DUCKDB_ERROR_EXECUTOR,
200            Self::Constraint => duckdb_error_type_DUCKDB_ERROR_CONSTRAINT,
201            Self::Index => duckdb_error_type_DUCKDB_ERROR_INDEX,
202            Self::Stat => duckdb_error_type_DUCKDB_ERROR_STAT,
203            Self::Connection => duckdb_error_type_DUCKDB_ERROR_CONNECTION,
204            Self::Syntax => duckdb_error_type_DUCKDB_ERROR_SYNTAX,
205            Self::Settings => duckdb_error_type_DUCKDB_ERROR_SETTINGS,
206            Self::Binder => duckdb_error_type_DUCKDB_ERROR_BINDER,
207            Self::Network => duckdb_error_type_DUCKDB_ERROR_NETWORK,
208            Self::Optimizer => duckdb_error_type_DUCKDB_ERROR_OPTIMIZER,
209            Self::NullPointer => duckdb_error_type_DUCKDB_ERROR_NULL_POINTER,
210            Self::Io => duckdb_error_type_DUCKDB_ERROR_IO,
211            Self::Interrupt => duckdb_error_type_DUCKDB_ERROR_INTERRUPT,
212            Self::Fatal => duckdb_error_type_DUCKDB_ERROR_FATAL,
213            Self::Internal => duckdb_error_type_DUCKDB_ERROR_INTERNAL,
214            Self::InvalidInput => duckdb_error_type_DUCKDB_ERROR_INVALID_INPUT,
215            Self::OutOfMemory => duckdb_error_type_DUCKDB_ERROR_OUT_OF_MEMORY,
216            Self::Permission => duckdb_error_type_DUCKDB_ERROR_PERMISSION,
217            Self::ParameterNotResolved => duckdb_error_type_DUCKDB_ERROR_PARAMETER_NOT_RESOLVED,
218            Self::ParameterNotAllowed => duckdb_error_type_DUCKDB_ERROR_PARAMETER_NOT_ALLOWED,
219            Self::Dependency => duckdb_error_type_DUCKDB_ERROR_DEPENDENCY,
220            Self::Http => duckdb_error_type_DUCKDB_ERROR_HTTP,
221            Self::MissingExtension => duckdb_error_type_DUCKDB_ERROR_MISSING_EXTENSION,
222            Self::Autoload => DUCKDB_ERROR_AUTOLOAD,
223            Self::Sequence => DUCKDB_ERROR_SEQUENCE,
224            Self::InvalidConfiguration => DUCKDB_INVALID_CONFIGURATION,
225            Self::DataCorruption => DUCKDB_ERROR_DATA_CORRUPTION,
226            Self::ResourceInUse => DUCKDB_ERROR_RESOURCE_IN_USE,
227        }
228    }
229
230    /// Converts from the `DuckDB` C API constant. Unknown values map to
231    /// [`Invalid`][DuckDbErrorType::Invalid].
232    #[must_use]
233    pub(crate) const fn from_raw(raw: duckdb_error_type) -> Self {
234        match raw {
235            x if x == duckdb_error_type_DUCKDB_ERROR_OUT_OF_RANGE => Self::OutOfRange,
236            x if x == duckdb_error_type_DUCKDB_ERROR_CONVERSION => Self::Conversion,
237            x if x == duckdb_error_type_DUCKDB_ERROR_UNKNOWN_TYPE => Self::UnknownType,
238            x if x == duckdb_error_type_DUCKDB_ERROR_DECIMAL => Self::Decimal,
239            x if x == duckdb_error_type_DUCKDB_ERROR_MISMATCH_TYPE => Self::MismatchType,
240            x if x == duckdb_error_type_DUCKDB_ERROR_DIVIDE_BY_ZERO => Self::DivideByZero,
241            x if x == duckdb_error_type_DUCKDB_ERROR_OBJECT_SIZE => Self::ObjectSize,
242            x if x == duckdb_error_type_DUCKDB_ERROR_INVALID_TYPE => Self::InvalidType,
243            x if x == duckdb_error_type_DUCKDB_ERROR_SERIALIZATION => Self::Serialization,
244            x if x == duckdb_error_type_DUCKDB_ERROR_TRANSACTION => Self::Transaction,
245            x if x == duckdb_error_type_DUCKDB_ERROR_NOT_IMPLEMENTED => Self::NotImplemented,
246            x if x == duckdb_error_type_DUCKDB_ERROR_EXPRESSION => Self::Expression,
247            x if x == duckdb_error_type_DUCKDB_ERROR_CATALOG => Self::Catalog,
248            x if x == duckdb_error_type_DUCKDB_ERROR_PARSER => Self::Parser,
249            x if x == duckdb_error_type_DUCKDB_ERROR_PLANNER => Self::Planner,
250            x if x == duckdb_error_type_DUCKDB_ERROR_SCHEDULER => Self::Scheduler,
251            x if x == duckdb_error_type_DUCKDB_ERROR_EXECUTOR => Self::Executor,
252            x if x == duckdb_error_type_DUCKDB_ERROR_CONSTRAINT => Self::Constraint,
253            x if x == duckdb_error_type_DUCKDB_ERROR_INDEX => Self::Index,
254            x if x == duckdb_error_type_DUCKDB_ERROR_STAT => Self::Stat,
255            x if x == duckdb_error_type_DUCKDB_ERROR_CONNECTION => Self::Connection,
256            x if x == duckdb_error_type_DUCKDB_ERROR_SYNTAX => Self::Syntax,
257            x if x == duckdb_error_type_DUCKDB_ERROR_SETTINGS => Self::Settings,
258            x if x == duckdb_error_type_DUCKDB_ERROR_BINDER => Self::Binder,
259            x if x == duckdb_error_type_DUCKDB_ERROR_NETWORK => Self::Network,
260            x if x == duckdb_error_type_DUCKDB_ERROR_OPTIMIZER => Self::Optimizer,
261            x if x == duckdb_error_type_DUCKDB_ERROR_NULL_POINTER => Self::NullPointer,
262            x if x == duckdb_error_type_DUCKDB_ERROR_IO => Self::Io,
263            x if x == duckdb_error_type_DUCKDB_ERROR_INTERRUPT => Self::Interrupt,
264            x if x == duckdb_error_type_DUCKDB_ERROR_FATAL => Self::Fatal,
265            x if x == duckdb_error_type_DUCKDB_ERROR_INTERNAL => Self::Internal,
266            x if x == duckdb_error_type_DUCKDB_ERROR_INVALID_INPUT => Self::InvalidInput,
267            x if x == duckdb_error_type_DUCKDB_ERROR_OUT_OF_MEMORY => Self::OutOfMemory,
268            x if x == duckdb_error_type_DUCKDB_ERROR_PERMISSION => Self::Permission,
269            x if x == duckdb_error_type_DUCKDB_ERROR_PARAMETER_NOT_RESOLVED => {
270                Self::ParameterNotResolved
271            }
272            x if x == duckdb_error_type_DUCKDB_ERROR_PARAMETER_NOT_ALLOWED => {
273                Self::ParameterNotAllowed
274            }
275            x if x == duckdb_error_type_DUCKDB_ERROR_DEPENDENCY => Self::Dependency,
276            x if x == duckdb_error_type_DUCKDB_ERROR_HTTP => Self::Http,
277            x if x == duckdb_error_type_DUCKDB_ERROR_MISSING_EXTENSION => Self::MissingExtension,
278            DUCKDB_ERROR_AUTOLOAD => Self::Autoload,
279            DUCKDB_ERROR_SEQUENCE => Self::Sequence,
280            DUCKDB_INVALID_CONFIGURATION => Self::InvalidConfiguration,
281            DUCKDB_ERROR_DATA_CORRUPTION => Self::DataCorruption,
282            DUCKDB_ERROR_RESOURCE_IN_USE => Self::ResourceInUse,
283            _ => Self::Invalid,
284        }
285    }
286
287    /// Returns a short, human-readable label for this error category.
288    #[must_use]
289    pub const fn as_str(self) -> &'static str {
290        match self {
291            Self::Invalid => "invalid",
292            Self::OutOfRange => "out of range",
293            Self::Conversion => "conversion",
294            Self::UnknownType => "unknown type",
295            Self::Decimal => "decimal",
296            Self::MismatchType => "type mismatch",
297            Self::DivideByZero => "divide by zero",
298            Self::ObjectSize => "object size",
299            Self::InvalidType => "invalid type",
300            Self::Serialization => "serialization",
301            Self::Transaction => "transaction",
302            Self::NotImplemented => "not implemented",
303            Self::Expression => "expression",
304            Self::Catalog => "catalog",
305            Self::Parser => "parser",
306            Self::Planner => "planner",
307            Self::Scheduler => "scheduler",
308            Self::Executor => "executor",
309            Self::Constraint => "constraint",
310            Self::Index => "index",
311            Self::Stat => "statistics",
312            Self::Connection => "connection",
313            Self::Syntax => "syntax",
314            Self::Settings => "settings",
315            Self::Binder => "binder",
316            Self::Network => "network",
317            Self::Optimizer => "optimizer",
318            Self::NullPointer => "null pointer",
319            Self::Io => "I/O",
320            Self::Interrupt => "interrupt",
321            Self::Fatal => "fatal",
322            Self::Internal => "internal",
323            Self::InvalidInput => "invalid input",
324            Self::OutOfMemory => "out of memory",
325            Self::Permission => "permission",
326            Self::ParameterNotResolved => "parameter not resolved",
327            Self::ParameterNotAllowed => "parameter not allowed",
328            Self::Dependency => "dependency",
329            Self::Http => "HTTP",
330            Self::MissingExtension => "missing extension",
331            Self::Autoload => "autoload",
332            Self::Sequence => "sequence",
333            Self::InvalidConfiguration => "invalid configuration",
334            Self::DataCorruption => "data corruption",
335            Self::ResourceInUse => "resource in use",
336        }
337    }
338}
339
340impl fmt::Display for DuckDbErrorType {
341    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342        f.write_str(self.as_str())
343    }
344}
345
346/// RAII wrapper for a `duckdb_error_data` handle.
347///
348/// Automatically destroyed when dropped. Carries a structured error category
349/// ([`DuckDbErrorType`]) and a human-readable message.
350///
351/// Implements [`Display`][std::fmt::Display] and [`std::error::Error`], and
352/// converts into [`ExtensionError`] via [`From`] (or
353/// [`into_extension_error`][ErrorData::into_extension_error]) so it can be
354/// propagated with `?`.
355pub struct ErrorData {
356    raw: duckdb_error_data,
357}
358
359impl ErrorData {
360    /// Creates a new structured error with the given category and message.
361    ///
362    /// An interior null byte in `message` is replaced by `?`, the same as
363    /// every other error path in the crate, so no part of the message is lost.
364    #[must_use]
365    pub fn new(error_type: DuckDbErrorType, message: &str) -> Self {
366        let c_msg = crate::callback::message_to_c_string(message);
367        // SAFETY: error_type.to_raw() is a valid duckdb_error_type and c_msg is a
368        // valid null-terminated string for the duration of the call.
369        let raw = unsafe { duckdb_create_error_data(error_type.to_raw(), c_msg.as_ptr()) };
370        Self { raw }
371    }
372
373    /// Wraps a raw `duckdb_error_data` handle, taking ownership.
374    ///
375    /// # Safety
376    ///
377    /// `raw` must be a `duckdb_error_data` returned by a `DuckDB` API call (it may
378    /// be null). The caller must not destroy the handle after this call.
379    #[inline]
380    #[must_use]
381    pub const unsafe fn from_raw(raw: duckdb_error_data) -> Self {
382        Self { raw }
383    }
384
385    /// Returns the raw handle without consuming the `ErrorData`.
386    #[inline]
387    #[must_use]
388    pub const fn as_raw(&self) -> duckdb_error_data {
389        self.raw
390    }
391
392    /// Returns `true` if the underlying handle is null.
393    #[inline]
394    #[must_use]
395    pub const fn is_null(&self) -> bool {
396        self.raw.is_null()
397    }
398
399    /// Returns `true` if this handle represents an actual error.
400    #[must_use]
401    pub fn has_error(&self) -> bool {
402        if self.raw.is_null() {
403            return false;
404        }
405        // SAFETY: self.raw is a non-null, valid duckdb_error_data.
406        unsafe { duckdb_error_data_has_error(self.raw) }
407    }
408
409    /// Returns the error category.
410    #[must_use]
411    pub fn error_type(&self) -> DuckDbErrorType {
412        if self.raw.is_null() {
413            return DuckDbErrorType::Invalid;
414        }
415        // SAFETY: self.raw is a non-null, valid duckdb_error_data.
416        let raw = unsafe { duckdb_error_data_error_type(self.raw) };
417        DuckDbErrorType::from_raw(raw)
418    }
419
420    /// Returns the error message, or `None` if the handle is null or the message
421    /// is not valid UTF-8.
422    ///
423    /// The returned string is owned by `DuckDB` and copied into a Rust `String`.
424    #[must_use]
425    pub fn message(&self) -> Option<String> {
426        if self.raw.is_null() {
427            return None;
428        }
429        // SAFETY: self.raw is a non-null, valid duckdb_error_data. The returned
430        // pointer is owned by the error data and remains valid while it lives.
431        let ptr = unsafe { duckdb_error_data_message(self.raw) };
432        if ptr.is_null() {
433            return None;
434        }
435        // SAFETY: ptr is a valid null-terminated string owned by the error data.
436        unsafe { CStr::from_ptr(ptr) }
437            .to_str()
438            .ok()
439            .map(String::from)
440    }
441
442    /// Consumes the `ErrorData` and converts it into an [`ExtensionError`].
443    ///
444    /// Useful for propagating a structured `DuckDB` error through `?`.
445    #[must_use]
446    pub fn into_extension_error(self) -> ExtensionError {
447        let msg = self
448            .message()
449            .unwrap_or_else(|| "unknown DuckDB error".to_owned());
450        ExtensionError::new(msg)
451    }
452
453    /// Consumes the `ErrorData` and returns the raw handle.
454    ///
455    /// The caller takes ownership and must call `duckdb_destroy_error_data`.
456    #[inline]
457    #[must_use]
458    pub const fn into_raw(self) -> duckdb_error_data {
459        let raw = self.raw;
460        std::mem::forget(self);
461        raw
462    }
463}
464
465impl Drop for ErrorData {
466    fn drop(&mut self) {
467        if !self.raw.is_null() {
468            // SAFETY: self.raw is a valid duckdb_error_data that we own.
469            unsafe { duckdb_destroy_error_data(&raw mut self.raw) };
470        }
471    }
472}
473
474impl fmt::Debug for ErrorData {
475    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
476        f.debug_struct("ErrorData")
477            .field("error_type", &self.error_type())
478            .field("message", &self.message())
479            .finish()
480    }
481}
482
483impl fmt::Display for ErrorData {
484    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
485        match self.message() {
486            Some(msg) => write!(f, "{}: {msg}", self.error_type()),
487            None => f.write_str(self.error_type().as_str()),
488        }
489    }
490}
491
492impl std::error::Error for ErrorData {}
493
494impl From<ErrorData> for ExtensionError {
495    #[inline]
496    fn from(err: ErrorData) -> Self {
497        err.into_extension_error()
498    }
499}
500
501/// Wraps an [`ExtensionError`]'s message as [`DuckDbErrorType::Invalid`]
502/// ("no specific category": an `ExtensionError` carries none).
503///
504/// This is what lets `?` propagate a [`Value`][crate::value::Value] or
505/// builder error inside an [`Appender::row`][crate::appender::Appender::row]
506/// closure, whose error type is `ErrorData` under `duckdb-1-5`:
507///
508/// ```rust,no_run
509/// use quack_rs::appender::Appender;
510/// use quack_rs::value::Value;
511///
512/// # fn demo(appender: &Appender) -> Result<(), quack_rs::error_data::ErrorData> {
513/// appender.row(|row| {
514///     let price = Value::decimal(9, 2, 1999)?; // `ExtensionError` -> `ErrorData`
515///     row.append_value(&price)
516/// })
517/// # }
518/// ```
519impl From<ExtensionError> for ErrorData {
520    fn from(err: ExtensionError) -> Self {
521        Self::new(DuckDbErrorType::Invalid, err.as_str())
522    }
523}
524
525/// Checks whether `bytes` form a valid UTF-8 string according to `DuckDB`'s
526/// validator (`DuckDB` 1.5.0+).
527///
528/// `DuckDB`'s rules match Rust's: every Unicode scalar value is accepted, and
529/// surrogates, overlong encodings, code points above `U+10FFFF`, truncated
530/// sequences and stray continuation bytes are rejected, exactly where
531/// [`std::str::from_utf8`] rejects them (checked over all 1,112,064 scalar
532/// values and each malformed class). Use this when you want `DuckDB`'s
533/// structured [`ErrorData`] for the failure; for a yes/no answer,
534/// `std::str::from_utf8` is equivalent and needs no engine.
535///
536/// # Errors
537///
538/// Returns the structured [`ErrorData`] describing the first validation failure.
539pub fn check_valid_utf8(bytes: &[u8]) -> Result<(), ErrorData> {
540    let len = idx_t::try_from(bytes.len()).unwrap_or(idx_t::MAX);
541    // SAFETY: bytes.as_ptr() is valid for `len` bytes; DuckDB only reads them.
542    let raw = unsafe { duckdb_valid_utf8_check(bytes.as_ptr().cast(), len) };
543    // SAFETY: duckdb_valid_utf8_check returns an owned duckdb_error_data handle.
544    let err = unsafe { ErrorData::from_raw(raw) };
545    if err.has_error() {
546        Err(err)
547    } else {
548        Ok(())
549    }
550}
551
552#[cfg(test)]
553mod tests {
554    use super::*;
555
556    const ALL_VARIANTS: [DuckDbErrorType; 45] = [
557        DuckDbErrorType::Invalid,
558        DuckDbErrorType::OutOfRange,
559        DuckDbErrorType::Conversion,
560        DuckDbErrorType::UnknownType,
561        DuckDbErrorType::Decimal,
562        DuckDbErrorType::MismatchType,
563        DuckDbErrorType::DivideByZero,
564        DuckDbErrorType::ObjectSize,
565        DuckDbErrorType::InvalidType,
566        DuckDbErrorType::Serialization,
567        DuckDbErrorType::Transaction,
568        DuckDbErrorType::NotImplemented,
569        DuckDbErrorType::Expression,
570        DuckDbErrorType::Catalog,
571        DuckDbErrorType::Parser,
572        DuckDbErrorType::Planner,
573        DuckDbErrorType::Scheduler,
574        DuckDbErrorType::Executor,
575        DuckDbErrorType::Constraint,
576        DuckDbErrorType::Index,
577        DuckDbErrorType::Stat,
578        DuckDbErrorType::Connection,
579        DuckDbErrorType::Syntax,
580        DuckDbErrorType::Settings,
581        DuckDbErrorType::Binder,
582        DuckDbErrorType::Network,
583        DuckDbErrorType::Optimizer,
584        DuckDbErrorType::NullPointer,
585        DuckDbErrorType::Io,
586        DuckDbErrorType::Interrupt,
587        DuckDbErrorType::Fatal,
588        DuckDbErrorType::Internal,
589        DuckDbErrorType::InvalidInput,
590        DuckDbErrorType::OutOfMemory,
591        DuckDbErrorType::Permission,
592        DuckDbErrorType::ParameterNotResolved,
593        DuckDbErrorType::ParameterNotAllowed,
594        DuckDbErrorType::Dependency,
595        DuckDbErrorType::Http,
596        DuckDbErrorType::MissingExtension,
597        DuckDbErrorType::Autoload,
598        DuckDbErrorType::Sequence,
599        DuckDbErrorType::InvalidConfiguration,
600        DuckDbErrorType::DataCorruption,
601        DuckDbErrorType::ResourceInUse,
602    ];
603
604    #[test]
605    fn error_types_past_missing_extension_are_recognised() {
606        // duckdb.h v1.5.5 numbers these 40, 41 and 42; they used to fall into
607        // the `_ => Invalid` arm.
608        assert_eq!(DuckDbErrorType::from_raw(40), DuckDbErrorType::Autoload);
609        assert_eq!(DuckDbErrorType::from_raw(41), DuckDbErrorType::Sequence);
610        assert_eq!(
611            DuckDbErrorType::from_raw(42),
612            DuckDbErrorType::InvalidConfiguration
613        );
614        // duckdb.h v2.0.0 adds 43 and 44.
615        assert_eq!(
616            DuckDbErrorType::from_raw(43),
617            DuckDbErrorType::DataCorruption
618        );
619        assert_eq!(
620            DuckDbErrorType::from_raw(44),
621            DuckDbErrorType::ResourceInUse
622        );
623        assert_eq!(DuckDbErrorType::from_raw(45), DuckDbErrorType::Invalid);
624    }
625
626    #[test]
627    fn error_type_round_trip_all_variants() {
628        for variant in ALL_VARIANTS {
629            let raw = variant.to_raw();
630            assert_eq!(
631                DuckDbErrorType::from_raw(raw),
632                variant,
633                "round-trip failed for {variant:?}"
634            );
635        }
636    }
637
638    #[test]
639    fn error_type_unknown_raw_maps_to_invalid() {
640        assert_eq!(DuckDbErrorType::from_raw(9999), DuckDbErrorType::Invalid);
641    }
642
643    #[test]
644    fn error_type_distinct_raw_values() {
645        for (i, a) in ALL_VARIANTS.iter().enumerate() {
646            for b in ALL_VARIANTS.iter().skip(i + 1) {
647                assert_ne!(
648                    a.to_raw(),
649                    b.to_raw(),
650                    "variants {a:?} and {b:?} share a raw value"
651                );
652            }
653        }
654    }
655
656    #[test]
657    fn null_error_data_has_no_error() {
658        let err = unsafe { ErrorData::from_raw(std::ptr::null_mut()) };
659        assert!(err.is_null());
660        assert!(!err.has_error());
661        assert_eq!(err.error_type(), DuckDbErrorType::Invalid);
662        assert!(err.message().is_none());
663    }
664
665    #[test]
666    fn into_raw_forgets_handle() {
667        let err = unsafe { ErrorData::from_raw(std::ptr::null_mut()) };
668        let raw = err.into_raw();
669        assert!(raw.is_null());
670    }
671
672    #[test]
673    fn error_type_display_matches_as_str() {
674        for variant in ALL_VARIANTS {
675            assert!(!variant.as_str().is_empty(), "{variant:?} has empty label");
676            assert_eq!(format!("{variant}"), variant.as_str());
677        }
678    }
679
680    #[test]
681    fn error_type_labels_are_distinct() {
682        for (i, a) in ALL_VARIANTS.iter().enumerate() {
683            for b in ALL_VARIANTS.iter().skip(i + 1) {
684                assert_ne!(a.as_str(), b.as_str(), "{a:?} and {b:?} share a label");
685            }
686        }
687    }
688
689    #[test]
690    fn null_error_data_debug_and_display() {
691        // Null handle: error_type()/message() short-circuit without FFI calls,
692        // so Debug/Display are safe to exercise in a unit test.
693        let err = unsafe { ErrorData::from_raw(std::ptr::null_mut()) };
694        assert_eq!(err.to_string(), "invalid");
695        let dbg = format!("{err:?}");
696        assert!(dbg.contains("ErrorData"), "debug was: {dbg}");
697        assert!(dbg.contains("Invalid"), "debug was: {dbg}");
698    }
699
700    #[test]
701    fn from_error_data_for_extension_error() {
702        let err = unsafe { ErrorData::from_raw(std::ptr::null_mut()) };
703        let ext: ExtensionError = err.into();
704        assert_eq!(ext.as_str(), "unknown DuckDB error");
705    }
706
707    #[test]
708    fn error_data_usable_as_std_error() {
709        fn takes_error(_e: &dyn std::error::Error) {}
710        let err = unsafe { ErrorData::from_raw(std::ptr::null_mut()) };
711        takes_error(&err);
712    }
713}