Skip to main content

quack_rs/
error.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//! Error types for `DuckDB` extension FFI error propagation.
7//!
8//! [`ExtensionError`] is the primary error type. It implements [`std::error::Error`],
9//! can be constructed from `&str` or `String`, and converts to a `CString` for
10//! passing to `access.set_error`.
11//!
12//! # Example
13//!
14//! ```rust
15//! use quack_rs::error::ExtensionError;
16//!
17//! let err = ExtensionError::from("Failed to register function");
18//! assert_eq!(err.to_string(), "Failed to register function");
19//! ```
20
21use std::ffi::CString;
22use std::fmt;
23
24/// The advice appended to every `duckdb_register_*_function failed` message.
25///
26/// The C API reports registration failure as a bare `DuckDBError` with no
27/// reason attached — there is no `duckdb_..._error` for it — so the message
28/// quack-rs can produce is only as useful as the list of causes it names.
29///
30/// What a name collision does depends on the kind of function, and only the
31/// cases `DuckDB` itself refuses end up here (checked on `DuckDB` 1.5.5):
32///
33/// - an **aggregate** cannot reuse any existing function or macro name —
34///   built-in or not, including its own earlier registration (e.g. on a
35///   retried `LOAD`): an aggregate catalog entry cannot be altered;
36/// - a **scalar** cannot take an aggregate's or a macro's name (the built-in
37///   `list_sum` is a macro).
38///
39/// A scalar over an existing scalar signature does not fail in `DuckDB` — it
40/// silently replaces it — so the scalar builders check for that themselves
41/// before registering. A copy function under an existing name does not fail
42/// either (`DuckDB` drops it and reports success); those builders also check
43/// first. Table functions do not use this hint: their failure carries its own
44/// message, which covers a duplicate name failing the call on v1.4.x (see
45/// `TableFunctionBuilder::register_with`).
46pub(crate) const REGISTRATION_FAILURE_HINT: &str =
47    "the C API reports no reason. The usual cause is a name DuckDB will not merge: an \
48     aggregate cannot reuse any existing function or macro name (including its own earlier \
49     registration, e.g. on a retried LOAD), and a scalar cannot take an aggregate's or a \
50     macro's name (the built-in `list_sum` is a macro) — check `SELECT function_name, \
51     function_type FROM duckdb_functions() WHERE function_name = '<name>'`. Otherwise a \
52     parameter or return type is invalid, or a required callback was never set.";
53
54/// An error that can occur during `DuckDB` extension initialization or registration.
55///
56/// This type is designed for use with the `?` operator inside the extension
57/// entry point. It can be reported back to `DuckDB` via `access.set_error`.
58///
59/// # Construction
60///
61/// ```rust
62/// use quack_rs::error::ExtensionError;
63///
64/// // From a string literal
65/// let e = ExtensionError::from("something went wrong");
66///
67/// // From a String
68/// let msg = format!("failed: {}", 42);
69/// let e = ExtensionError::from(msg);
70///
71/// // Wrapping another error
72/// let parse_err: Result<i32, _> = "not a number".parse();
73/// let e = parse_err.map_err(ExtensionError::from_error);
74/// ```
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct ExtensionError {
77    message: String,
78}
79
80impl ExtensionError {
81    /// Creates a new `ExtensionError` with the given message.
82    ///
83    /// # Example
84    ///
85    /// ```rust
86    /// use quack_rs::error::ExtensionError;
87    ///
88    /// let err = ExtensionError::new("registration failed");
89    /// assert_eq!(err.to_string(), "registration failed");
90    /// ```
91    #[inline]
92    pub fn new(message: impl Into<String>) -> Self {
93        Self {
94            message: message.into(),
95        }
96    }
97
98    /// Wraps any `std::error::Error` into an `ExtensionError`.
99    ///
100    /// # Example
101    ///
102    /// ```rust
103    /// use quack_rs::error::ExtensionError;
104    ///
105    /// let result: Result<i32, _> = "abc".parse::<i32>();
106    /// let err = result.map_err(ExtensionError::from_error);
107    /// assert!(err.is_err());
108    /// ```
109    #[inline]
110    pub fn from_error<E: std::error::Error>(e: E) -> Self {
111        Self {
112            message: e.to_string(),
113        }
114    }
115
116    /// Converts this error into a `CString` suitable for passing to `set_error`.
117    ///
118    /// A null byte in the message (valid in a Rust `String`, not in a C
119    /// string) is replaced by `?`, as on every error path in this crate
120    /// ([`message_to_c_string`][crate::callback::message_to_c_string]), so the
121    /// text after it is not lost.
122    ///
123    /// # Example
124    ///
125    /// ```rust
126    /// use quack_rs::error::ExtensionError;
127    ///
128    /// let err = ExtensionError::new("oops");
129    /// assert_eq!(err.to_c_string().to_str().unwrap(), "oops");
130    /// let err = ExtensionError::new("a\0b");
131    /// assert_eq!(err.to_c_string().to_str().unwrap(), "a?b");
132    /// ```
133    #[must_use]
134    pub fn to_c_string(&self) -> CString {
135        crate::callback::message_to_c_string(&self.message)
136    }
137
138    /// Returns the error message as a string slice.
139    ///
140    /// # Example
141    ///
142    /// ```rust
143    /// use quack_rs::error::ExtensionError;
144    ///
145    /// let err = ExtensionError::new("bad input");
146    /// assert_eq!(err.as_str(), "bad input");
147    /// ```
148    #[must_use]
149    #[inline]
150    pub fn as_str(&self) -> &str {
151        &self.message
152    }
153}
154
155impl fmt::Display for ExtensionError {
156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157        f.write_str(&self.message)
158    }
159}
160
161impl std::error::Error for ExtensionError {}
162
163impl From<&str> for ExtensionError {
164    #[inline]
165    fn from(s: &str) -> Self {
166        Self::new(s)
167    }
168}
169
170impl From<String> for ExtensionError {
171    #[inline]
172    fn from(s: String) -> Self {
173        Self { message: s }
174    }
175}
176
177impl From<Box<dyn std::error::Error>> for ExtensionError {
178    #[inline]
179    fn from(e: Box<dyn std::error::Error>) -> Self {
180        Self {
181            message: e.to_string(),
182        }
183    }
184}
185
186impl From<Box<dyn std::error::Error + Send + Sync>> for ExtensionError {
187    #[inline]
188    fn from(e: Box<dyn std::error::Error + Send + Sync>) -> Self {
189        Self {
190            message: e.to_string(),
191        }
192    }
193}
194
195impl From<std::io::Error> for ExtensionError {
196    #[inline]
197    fn from(e: std::io::Error) -> Self {
198        Self {
199            message: e.to_string(),
200        }
201    }
202}
203
204impl From<std::ffi::NulError> for ExtensionError {
205    #[inline]
206    fn from(e: std::ffi::NulError) -> Self {
207        Self {
208            message: e.to_string(),
209        }
210    }
211}
212
213impl From<std::fmt::Error> for ExtensionError {
214    #[inline]
215    fn from(e: std::fmt::Error) -> Self {
216        Self {
217            message: e.to_string(),
218        }
219    }
220}
221
222/// Convenience type alias for `Result<T, ExtensionError>`.
223pub type ExtResult<T> = Result<T, ExtensionError>;
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn new_creates_with_message() {
231        let err = ExtensionError::new("test error");
232        assert_eq!(err.to_string(), "test error");
233        assert_eq!(err.as_str(), "test error");
234    }
235
236    #[test]
237    fn from_str() {
238        let err = ExtensionError::from("from str");
239        assert_eq!(err.message, "from str");
240    }
241
242    #[test]
243    fn from_string() {
244        let s = String::from("from String");
245        let err = ExtensionError::from(s);
246        assert_eq!(err.message, "from String");
247    }
248
249    #[test]
250    fn from_error_wraps_display() {
251        let parse_err = "abc".parse::<i32>().unwrap_err();
252        let err = ExtensionError::from_error(parse_err);
253        assert_ne!(err.message, "");
254    }
255
256    #[test]
257    fn to_c_string_normal() {
258        let err = ExtensionError::new("hello world");
259        let cstr = err.to_c_string();
260        assert_eq!(cstr.to_str().unwrap(), "hello world");
261    }
262
263    #[test]
264    fn to_c_string_with_null_byte() {
265        // An embedded null byte is replaced, keeping the rest of the message.
266        let err = ExtensionError::new("before\0after");
267        let cstr = err.to_c_string();
268        assert_eq!(cstr.to_str().unwrap(), "before?after");
269    }
270
271    #[test]
272    fn to_c_string_empty() {
273        let err = ExtensionError::new("");
274        let cstr = err.to_c_string();
275        assert_eq!(cstr.to_str().unwrap(), "");
276    }
277
278    #[test]
279    fn display_impl() {
280        let err = ExtensionError::new("display test");
281        let s = format!("{err}");
282        assert_eq!(s, "display test");
283    }
284
285    #[test]
286    fn debug_impl() {
287        let err = ExtensionError::new("debug");
288        let s = format!("{err:?}");
289        assert!(s.contains("debug"));
290    }
291
292    #[test]
293    fn clone_eq() {
294        let err1 = ExtensionError::new("clone test");
295        let err2 = err1.clone();
296        assert_eq!(err1, err2);
297    }
298
299    #[test]
300    fn from_box_dyn_error() {
301        let boxed: Box<dyn std::error::Error> = "abc".parse::<i32>().unwrap_err().into();
302        let err = ExtensionError::from(boxed);
303        assert_ne!(err.message, "");
304    }
305
306    #[test]
307    fn question_mark_operator_with_str() {
308        fn fails() -> Result<(), ExtensionError> {
309            Err("explicit error")?;
310            Ok(())
311        }
312        assert_eq!(fails().unwrap_err().as_str(), "explicit error");
313    }
314
315    #[test]
316    fn from_io_error() {
317        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
318        let err = ExtensionError::from(io_err);
319        assert_eq!(err.as_str(), "file not found");
320    }
321
322    #[test]
323    fn question_mark_with_io_error() {
324        fn fails() -> Result<(), ExtensionError> {
325            Err(std::io::Error::other("runtime init failed"))?;
326            Ok(())
327        }
328        assert_eq!(fails().unwrap_err().as_str(), "runtime init failed");
329    }
330
331    #[test]
332    fn from_nul_error() {
333        let nul_err = std::ffi::CString::new("hello\0world").unwrap_err();
334        let err = ExtensionError::from(nul_err);
335        assert_ne!(err.as_str(), "");
336    }
337
338    #[test]
339    fn from_fmt_error() {
340        let fmt_err = std::fmt::Error;
341        let err = ExtensionError::from(fmt_err);
342        assert_ne!(err.as_str(), "");
343    }
344
345    #[test]
346    fn to_c_string_leading_null_byte() {
347        let err = ExtensionError::new("\0trailing");
348        let cstr = err.to_c_string();
349        assert_eq!(cstr.to_str().unwrap(), "?trailing");
350    }
351
352    #[test]
353    fn to_c_string_multiple_null_bytes() {
354        let err = ExtensionError::new("first\0second\0third");
355        let cstr = err.to_c_string();
356        assert_eq!(cstr.to_str().unwrap(), "first?second?third");
357    }
358
359    #[test]
360    fn from_box_dyn_error_send_sync() {
361        let boxed: Box<dyn std::error::Error + Send + Sync> =
362            "abc".parse::<i32>().unwrap_err().into();
363        let err = ExtensionError::from(boxed);
364        assert_ne!(err.message, "");
365    }
366
367    #[test]
368    fn ext_result_alias() {
369        // Verify ExtResult<T> alias works as expected
370        let ok_val: ExtResult<i32> = Ok(42);
371        assert!(ok_val.is_ok());
372
373        let err_val: ExtResult<i32> = Err(ExtensionError::new("fail"));
374        assert!(err_val.is_err());
375    }
376}