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/// Checks whether `bytes` form a valid UTF-8 string according to `DuckDB`'s
502/// validator (`DuckDB` 1.5.0+).
503///
504/// `DuckDB`'s rules match Rust's: every Unicode scalar value is accepted, and
505/// surrogates, overlong encodings, code points above `U+10FFFF`, truncated
506/// sequences and stray continuation bytes are rejected, exactly where
507/// [`std::str::from_utf8`] rejects them (checked over all 1,112,064 scalar
508/// values and each malformed class). Use this when you want `DuckDB`'s
509/// structured [`ErrorData`] for the failure; for a yes/no answer,
510/// `std::str::from_utf8` is equivalent and needs no engine.
511///
512/// # Errors
513///
514/// Returns the structured [`ErrorData`] describing the first validation failure.
515pub fn check_valid_utf8(bytes: &[u8]) -> Result<(), ErrorData> {
516    let len = idx_t::try_from(bytes.len()).unwrap_or(idx_t::MAX);
517    // SAFETY: bytes.as_ptr() is valid for `len` bytes; DuckDB only reads them.
518    let raw = unsafe { duckdb_valid_utf8_check(bytes.as_ptr().cast(), len) };
519    // SAFETY: duckdb_valid_utf8_check returns an owned duckdb_error_data handle.
520    let err = unsafe { ErrorData::from_raw(raw) };
521    if err.has_error() {
522        Err(err)
523    } else {
524        Ok(())
525    }
526}
527
528#[cfg(test)]
529mod tests {
530    use super::*;
531
532    const ALL_VARIANTS: [DuckDbErrorType; 45] = [
533        DuckDbErrorType::Invalid,
534        DuckDbErrorType::OutOfRange,
535        DuckDbErrorType::Conversion,
536        DuckDbErrorType::UnknownType,
537        DuckDbErrorType::Decimal,
538        DuckDbErrorType::MismatchType,
539        DuckDbErrorType::DivideByZero,
540        DuckDbErrorType::ObjectSize,
541        DuckDbErrorType::InvalidType,
542        DuckDbErrorType::Serialization,
543        DuckDbErrorType::Transaction,
544        DuckDbErrorType::NotImplemented,
545        DuckDbErrorType::Expression,
546        DuckDbErrorType::Catalog,
547        DuckDbErrorType::Parser,
548        DuckDbErrorType::Planner,
549        DuckDbErrorType::Scheduler,
550        DuckDbErrorType::Executor,
551        DuckDbErrorType::Constraint,
552        DuckDbErrorType::Index,
553        DuckDbErrorType::Stat,
554        DuckDbErrorType::Connection,
555        DuckDbErrorType::Syntax,
556        DuckDbErrorType::Settings,
557        DuckDbErrorType::Binder,
558        DuckDbErrorType::Network,
559        DuckDbErrorType::Optimizer,
560        DuckDbErrorType::NullPointer,
561        DuckDbErrorType::Io,
562        DuckDbErrorType::Interrupt,
563        DuckDbErrorType::Fatal,
564        DuckDbErrorType::Internal,
565        DuckDbErrorType::InvalidInput,
566        DuckDbErrorType::OutOfMemory,
567        DuckDbErrorType::Permission,
568        DuckDbErrorType::ParameterNotResolved,
569        DuckDbErrorType::ParameterNotAllowed,
570        DuckDbErrorType::Dependency,
571        DuckDbErrorType::Http,
572        DuckDbErrorType::MissingExtension,
573        DuckDbErrorType::Autoload,
574        DuckDbErrorType::Sequence,
575        DuckDbErrorType::InvalidConfiguration,
576        DuckDbErrorType::DataCorruption,
577        DuckDbErrorType::ResourceInUse,
578    ];
579
580    #[test]
581    fn error_types_past_missing_extension_are_recognised() {
582        // duckdb.h v1.5.5 numbers these 40, 41 and 42; they used to fall into
583        // the `_ => Invalid` arm.
584        assert_eq!(DuckDbErrorType::from_raw(40), DuckDbErrorType::Autoload);
585        assert_eq!(DuckDbErrorType::from_raw(41), DuckDbErrorType::Sequence);
586        assert_eq!(
587            DuckDbErrorType::from_raw(42),
588            DuckDbErrorType::InvalidConfiguration
589        );
590        // duckdb.h v2.0.0 adds 43 and 44.
591        assert_eq!(
592            DuckDbErrorType::from_raw(43),
593            DuckDbErrorType::DataCorruption
594        );
595        assert_eq!(
596            DuckDbErrorType::from_raw(44),
597            DuckDbErrorType::ResourceInUse
598        );
599        assert_eq!(DuckDbErrorType::from_raw(45), DuckDbErrorType::Invalid);
600    }
601
602    #[test]
603    fn error_type_round_trip_all_variants() {
604        for variant in ALL_VARIANTS {
605            let raw = variant.to_raw();
606            assert_eq!(
607                DuckDbErrorType::from_raw(raw),
608                variant,
609                "round-trip failed for {variant:?}"
610            );
611        }
612    }
613
614    #[test]
615    fn error_type_unknown_raw_maps_to_invalid() {
616        assert_eq!(DuckDbErrorType::from_raw(9999), DuckDbErrorType::Invalid);
617    }
618
619    #[test]
620    fn error_type_distinct_raw_values() {
621        for (i, a) in ALL_VARIANTS.iter().enumerate() {
622            for b in ALL_VARIANTS.iter().skip(i + 1) {
623                assert_ne!(
624                    a.to_raw(),
625                    b.to_raw(),
626                    "variants {a:?} and {b:?} share a raw value"
627                );
628            }
629        }
630    }
631
632    #[test]
633    fn null_error_data_has_no_error() {
634        let err = unsafe { ErrorData::from_raw(std::ptr::null_mut()) };
635        assert!(err.is_null());
636        assert!(!err.has_error());
637        assert_eq!(err.error_type(), DuckDbErrorType::Invalid);
638        assert!(err.message().is_none());
639    }
640
641    #[test]
642    fn into_raw_forgets_handle() {
643        let err = unsafe { ErrorData::from_raw(std::ptr::null_mut()) };
644        let raw = err.into_raw();
645        assert!(raw.is_null());
646    }
647
648    #[test]
649    fn error_type_display_matches_as_str() {
650        for variant in ALL_VARIANTS {
651            assert!(!variant.as_str().is_empty(), "{variant:?} has empty label");
652            assert_eq!(format!("{variant}"), variant.as_str());
653        }
654    }
655
656    #[test]
657    fn error_type_labels_are_distinct() {
658        for (i, a) in ALL_VARIANTS.iter().enumerate() {
659            for b in ALL_VARIANTS.iter().skip(i + 1) {
660                assert_ne!(a.as_str(), b.as_str(), "{a:?} and {b:?} share a label");
661            }
662        }
663    }
664
665    #[test]
666    fn null_error_data_debug_and_display() {
667        // Null handle: error_type()/message() short-circuit without FFI calls,
668        // so Debug/Display are safe to exercise in a unit test.
669        let err = unsafe { ErrorData::from_raw(std::ptr::null_mut()) };
670        assert_eq!(err.to_string(), "invalid");
671        let dbg = format!("{err:?}");
672        assert!(dbg.contains("ErrorData"), "debug was: {dbg}");
673        assert!(dbg.contains("Invalid"), "debug was: {dbg}");
674    }
675
676    #[test]
677    fn from_error_data_for_extension_error() {
678        let err = unsafe { ErrorData::from_raw(std::ptr::null_mut()) };
679        let ext: ExtensionError = err.into();
680        assert_eq!(ext.as_str(), "unknown DuckDB error");
681    }
682
683    #[test]
684    fn error_data_usable_as_std_error() {
685        fn takes_error(_e: &dyn std::error::Error) {}
686        let err = unsafe { ErrorData::from_raw(std::ptr::null_mut()) };
687        takes_error(&err);
688    }
689}