Skip to main content

quack_rs/cast/
builder.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//! Builder for registering custom `DuckDB` cast functions.
7
8use std::os::raw::c_void;
9
10use libduckdb_sys::{
11    duckdb_cast_function_get_cast_mode, duckdb_cast_function_get_extra_info,
12    duckdb_cast_function_set_error, duckdb_cast_function_set_extra_info,
13    duckdb_cast_function_set_function, duckdb_cast_function_set_implicit_cast_cost,
14    duckdb_cast_function_set_row_error, duckdb_cast_function_set_source_type,
15    duckdb_cast_function_set_target_type, duckdb_cast_mode_DUCKDB_CAST_TRY, duckdb_connection,
16    duckdb_create_cast_function, duckdb_delete_callback_t, duckdb_destroy_cast_function,
17    duckdb_function_info, duckdb_register_cast_function, duckdb_vector, idx_t, DuckDBSuccess,
18};
19
20use crate::error::ExtensionError;
21use crate::table::cstr::error_cstring;
22use crate::types::logical_type::SlotCheck;
23use crate::types::{LogicalType, TypeId};
24
25// ── Cast mode ─────────────────────────────────────────────────────────────────
26
27/// Whether `DuckDB` wants cast failures thrown or collected.
28///
29/// In [`Try`][CastMode::Try] mode, conversion failures should write `NULL` for
30/// the failed row and call [`CastFunctionInfo::set_row_error`], and the
31/// callback should still return `false` if any row failed. See [`CastFn`] for
32/// what `DuckDB` does with the callback's return value in each mode — in
33/// particular, returning `false` in `Try` mode does **not** null anything.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum CastMode {
36    /// Failures are errors: a regular `CAST`, including the implicit casts
37    /// `DuckDB` inserts into a query.
38    Normal,
39    /// Failures are collected: `TRY_CAST`, and the casts `DuckDB` applies to
40    /// single values internally (`Value::CastAs`, as when a table function's
41    /// argument is converted to its parameter type), which throw when the
42    /// callback returns `false`.
43    Try,
44}
45
46impl CastMode {
47    const fn from_raw(raw: libduckdb_sys::duckdb_cast_mode) -> Self {
48        if raw == duckdb_cast_mode_DUCKDB_CAST_TRY {
49            Self::Try
50        } else {
51            Self::Normal
52        }
53    }
54}
55
56// ── Callback info wrapper ──────────────────────────────────────────────────────
57
58/// Ergonomic wrapper around the `duckdb_function_info` handle provided to a
59/// cast callback.
60///
61/// Exposes the cast-specific methods that are only meaningful inside a cast
62/// function callback.
63pub struct CastFunctionInfo {
64    info: duckdb_function_info,
65}
66
67impl CastFunctionInfo {
68    /// Wraps a raw `duckdb_function_info` provided by `DuckDB` inside a cast
69    /// callback.
70    ///
71    /// # Safety
72    ///
73    /// `info` must be a valid `duckdb_function_info` passed by `DuckDB` to a
74    /// cast callback.
75    #[inline]
76    #[must_use]
77    pub const unsafe fn new(info: duckdb_function_info) -> Self {
78        Self { info }
79    }
80
81    /// Returns whether this invocation is a `TRY_CAST` or a regular `CAST`.
82    ///
83    /// Check this inside your callback to decide between aborting on error
84    /// ([`CastMode::Normal`]) and producing `NULL` with a per-row error
85    /// ([`CastMode::Try`]).
86    #[must_use]
87    pub fn cast_mode(&self) -> CastMode {
88        // SAFETY: self.info is valid per constructor contract.
89        let raw = unsafe { duckdb_cast_function_get_cast_mode(self.info) };
90        CastMode::from_raw(raw)
91    }
92
93    /// Retrieves the extra-info pointer previously set via
94    /// [`CastFunctionBuilder::extra_info`].
95    ///
96    /// Returns a raw `*mut c_void`.  Cast it back to your concrete type.
97    ///
98    /// # Safety
99    ///
100    /// The returned pointer is only valid as long as the cast function is
101    /// registered and `DuckDB` has not yet called the destructor.
102    #[must_use]
103    pub unsafe fn get_extra_info(&self) -> *mut c_void {
104        // SAFETY: self.info is valid per constructor contract.
105        unsafe { duckdb_cast_function_get_extra_info(self.info) }
106    }
107
108    /// Borrows the extra info set with
109    /// [`CastFunctionBuilder::extra_info_typed`] as a `T`; `None` when none
110    /// was set or it holds another type.
111    ///
112    /// # Safety
113    ///
114    /// This cast's extra info, if any, was set through `extra_info_typed` and
115    /// not through the raw [`extra_info`][CastFunctionBuilder::extra_info]:
116    /// the type tag read here is the one `extra_info_typed` writes, and a raw
117    /// pointer carries none.
118    // One FFI call (`get_extra_info`) then the tag check, whose mutants
119    // `extra_info::typed_tests` kill; the `-> None` mutant needs a live engine.
120    #[cfg_attr(test, mutants::skip)]
121    #[must_use]
122    pub unsafe fn extra_info_ref<T: 'static>(&self) -> Option<&T> {
123        // SAFETY: the pointer is null or tagged (this method's contract);
124        // DuckDB keeps it alive while the cast is registered, which outlasts
125        // this callback and so `&self`.
126        unsafe { crate::extra_info::tagged_ref(self.get_extra_info()) }
127    }
128
129    /// Records the error `DuckDB` raises when the callback returns `false`.
130    ///
131    /// Use this only in [`CastMode::Normal`], where returning `false` fails the
132    /// query with this message as a `Conversion Error`. In [`CastMode::Try`]
133    /// the message is kept but the query does not fail, and no row becomes
134    /// `NULL` because of it: use [`set_row_error`][Self::set_row_error] for
135    /// every failed row instead.
136    ///
137    /// An interior null byte in `message` is replaced by `?`. An empty message is replaced by
138    /// [`EMPTY_ERROR_PLACEHOLDER`][Self::EMPTY_ERROR_PLACEHOLDER].
139    #[cfg_attr(test, mutants::skip)]
140    pub fn set_error(&self, message: &str) {
141        let c_msg = error_cstring(message, Self::EMPTY_ERROR_PLACEHOLDER);
142        // SAFETY: self.info is valid per constructor contract.
143        unsafe {
144            duckdb_cast_function_set_error(self.info, c_msg.as_ptr());
145        }
146    }
147
148    /// Reports a per-row conversion failure and sets `row` of `output` to
149    /// `NULL`.
150    ///
151    /// `duckdb_cast_function_set_row_error` does both: it records `message` as
152    /// the cast's error message and calls `FlatVector::SetNull(output, row)`
153    /// (`src/main/capi/cast_function-c.cpp`). In [`CastMode::Try`] this is the
154    /// only way a row becomes `NULL`; in [`CastMode::Normal`] the message is
155    /// what the query fails with once the callback returns `false`.
156    ///
157    /// An interior null byte in `message` is replaced by `?`. An empty message is replaced by
158    /// [`EMPTY_ERROR_PLACEHOLDER`][Self::EMPTY_ERROR_PLACEHOLDER].
159    ///
160    /// # Safety
161    ///
162    /// - `output` must be the same `duckdb_vector` passed to the cast callback.
163    /// - `row` must be less than the `count` passed to the cast callback.
164    ///   `DuckDB` does not check it: the validity-mask bounds check is a
165    ///   `D_ASSERT`, compiled out of release builds
166    ///   (`src/include/duckdb/common/types/validity_mask.hpp`), so an
167    ///   out-of-range `row` writes past the end of the validity mask.
168    pub unsafe fn set_row_error(&self, message: &str, row: idx_t, output: duckdb_vector) {
169        let c_msg = error_cstring(message, Self::EMPTY_ERROR_PLACEHOLDER);
170        // SAFETY: self.info is valid; output and row are caller-supplied.
171        unsafe {
172            duckdb_cast_function_set_row_error(self.info, c_msg.as_ptr(), row, output);
173        }
174    }
175
176    /// The message [`set_error`][Self::set_error] and
177    /// [`set_row_error`][Self::set_row_error] report in place of an empty one.
178    ///
179    /// Without it, `DuckDB` fails the query with `Conversion Error: ` followed
180    /// by nothing.
181    pub const EMPTY_ERROR_PLACEHOLDER: &'static str =
182        "cast function reported an error without a message";
183}
184
185// ── Callback type alias ────────────────────────────────────────────────────────
186
187/// The cast function callback signature.
188///
189/// - `info`   — cast function info; use [`CastFunctionInfo`] to wrap it.
190/// - `count`  — number of rows in this chunk.
191/// - `input`  — source vector (read from this).
192/// - `output` — destination vector (write results here).
193///
194/// # The return value
195///
196/// Return `true` when every row converted. What `false` does depends on the
197/// [`CastMode`]:
198///
199/// - **`Normal`** (`CAST`): the query fails with a `Conversion Error`
200///   carrying the message from [`CastFunctionInfo::set_error`] or
201///   [`set_row_error`][CastFunctionInfo::set_row_error]. Set one before
202///   returning `false`. With none, a [`cast_callback!`][crate::cast_callback]
203///   function reports
204///   [`CAST_FAILED_WITHOUT_MESSAGE`][crate::callback::CAST_FAILED_WITHOUT_MESSAGE];
205///   a hand-written callback makes `DuckDB` report `Conversion Error: `
206///   followed by nothing.
207/// - **`Try`** in a `TRY_CAST`: **nothing**. `DuckDB` discards the return
208///   value (`src/execution/expression_executor/execute_cast.cpp` calls the
209///   bound cast function and ignores what it returns; `CAPICastFunction` only
210///   records the message). Every row of `output` is returned as it stands —
211///   a row the callback never wrote holds whatever the vector held before,
212///   which can be a previous chunk's value. So in `Try` mode, call
213///   [`set_row_error`][CastFunctionInfo::set_row_error] (or set the row to
214///   `NULL` yourself) for **every** row that failed; returning `false` is not
215///   a substitute.
216/// - **`Try`** in an internal value cast (`Value::CastAs`, used for example to
217///   convert a table function's argument to its parameter type): `false`
218///   makes `DuckDB` throw `Failed to cast value:` followed by the message you
219///   set; `true` returns the row as written, so a failed row you nulled
220///   becomes a silent `NULL` argument.
221///
222/// So null each failed row **and** return `false` if any row failed: that is
223/// right in all three cases, and it is what `DuckDB`'s own casts do — their
224/// `TRY_CAST` loops null each failed row and return `false` as a summary.
225///
226/// A panic inside a [`cast_callback!`][crate::cast_callback] body is the one
227/// case quack-rs handles for you: in `Try` mode every row of the chunk is set
228/// to `NULL`, because what the body had written before it panicked cannot be
229/// trusted.
230pub type CastFn = unsafe extern "C" fn(
231    info: duckdb_function_info,
232    count: idx_t,
233    input: duckdb_vector,
234    output: duckdb_vector,
235) -> bool;
236
237// ── Builder ────────────────────────────────────────────────────────────────────
238
239/// Builder for registering a custom `DuckDB` cast function.
240///
241/// A cast function converts values from a **source** type to a **target** type.
242/// Registering a cast lets `DuckDB` use it both for explicit
243/// `CAST(x AS Target)` syntax and (if an implicit cost is set) for automatic
244/// coercions.
245///
246/// # Example
247///
248/// ```rust,no_run
249/// use quack_rs::cast::{CastFunctionBuilder, CastFunctionInfo, CastMode};
250/// use quack_rs::types::TypeId;
251/// use libduckdb_sys::{duckdb_function_info, duckdb_vector, idx_t};
252///
253/// unsafe extern "C" fn my_cast(
254///     _info: duckdb_function_info,
255///     _count: idx_t,
256///     _input: duckdb_vector,
257///     _output: duckdb_vector,
258/// ) -> bool {
259///     true // implement real conversion here
260/// }
261///
262/// // fn register(con: libduckdb_sys::duckdb_connection)
263/// //     -> Result<(), quack_rs::error::ExtensionError>
264/// // {
265/// //     unsafe {
266/// //         CastFunctionBuilder::new(TypeId::Varchar, TypeId::Integer)
267/// //             .function(my_cast)
268/// //             .register(con)
269/// //     }
270/// // }
271/// ```
272#[must_use]
273pub struct CastFunctionBuilder {
274    source: Option<TypeId>,
275    source_logical: Option<LogicalType>,
276    target: Option<TypeId>,
277    target_logical: Option<LogicalType>,
278    function: Option<CastFn>,
279    implicit_cost: Option<i64>,
280    extra_info: Option<crate::extra_info::ExtraInfo>,
281}
282
283// SAFETY: moving a builder to another thread moves ownership of three kinds of
284// raw handle, and none of them has thread affinity:
285// - `LogicalType` owns a heap-allocated C++ `duckdb::LogicalType`; its type info
286//   is held by a `shared_ptr` (atomic refcount), and `duckdb_destroy_logical_type`
287//   is a plain `delete` that any thread may run.
288// - `CastFn` is a plain function pointer.
289// - `ExtraInfo` holds the user's `extra_info` pointer and may run its destructor
290//   on whichever thread drops the builder. That is only sound for a pointee that
291//   is `Send`, and `extra_info` is an `unsafe fn` whose contract requires exactly
292//   that (`Send + Sync`, because DuckDB reads it from every thread that casts).
293// The builder is not `Sync`: nothing here is shared, only moved.
294#[allow(clippy::non_send_fields_in_send_ty)]
295unsafe impl Send for CastFunctionBuilder {}
296
297impl CastFunctionBuilder {
298    /// Creates a new builder that will cast `source` values into `target` values.
299    pub const fn new(source: TypeId, target: TypeId) -> Self {
300        Self {
301            source: Some(source),
302            source_logical: None,
303            target: Some(target),
304            target_logical: None,
305            function: None,
306            implicit_cost: None,
307            extra_info: None,
308        }
309    }
310
311    /// Creates a new builder using [`LogicalType`]s for source and target.
312    ///
313    /// Use this when the source or target types are complex (e.g.
314    /// `DECIMAL(18, 3)`, `LIST(VARCHAR)`, etc.) and cannot be expressed as
315    /// simple [`TypeId`] values.
316    pub fn new_logical(source: LogicalType, target: LogicalType) -> Self {
317        Self {
318            source: None,
319            source_logical: Some(source),
320            target: None,
321            target_logical: Some(target),
322            function: None,
323            implicit_cost: None,
324            extra_info: None,
325        }
326    }
327
328    /// Returns the source type this cast converts from (if set via [`new`][Self::new]).
329    ///
330    /// Returns `None` if the source was set via [`new_logical`][Self::new_logical].
331    ///
332    /// Useful for introspection and for [`MockRegistrar`][crate::testing::MockRegistrar].
333    pub const fn source(&self) -> Option<TypeId> {
334        self.source
335    }
336
337    /// Returns the target type this cast converts to (if set via [`new`][Self::new]).
338    ///
339    /// Returns `None` if the target was set via [`new_logical`][Self::new_logical].
340    ///
341    /// Useful for introspection and for [`MockRegistrar`][crate::testing::MockRegistrar].
342    pub const fn target(&self) -> Option<TypeId> {
343        self.target
344    }
345
346    /// Sets the cast callback.
347    pub fn function(mut self, f: CastFn) -> Self {
348        self.function = Some(f);
349        self
350    }
351
352    /// Sets the implicit cast cost.
353    ///
354    /// When a non-negative cost is provided, `DuckDB` may use this cast
355    /// automatically in expressions where an implicit coercion is needed.
356    /// Lower cost means higher priority. A negative cost or omitting this
357    /// method makes the cast explicit-only.
358    pub const fn implicit_cost(mut self, cost: i64) -> Self {
359        self.implicit_cost = Some(cost);
360        self
361    }
362
363    /// Attaches extra data to the cast function.
364    ///
365    /// The pointer is available inside the callback via
366    /// [`CastFunctionInfo::get_extra_info`].
367    ///
368    /// # Safety
369    ///
370    /// - `ptr` must remain valid until `DuckDB` calls `destroy`, or for the
371    ///   lifetime of the database if `destroy` is `None`.
372    /// - The pointee must be `Send + Sync`. `DuckDB` hands the same pointer to
373    ///   the cast callback on every thread that executes the cast, possibly at
374    ///   the same moment, and `destroy` runs on whichever thread releases the
375    ///   last reference — or, if the builder is dropped unregistered, on the
376    ///   thread that drops it (the builder is `Send`). Shared mutable state
377    ///   behind the pointer needs a `Mutex` or atomics.
378    pub unsafe fn extra_info(
379        mut self,
380        ptr: *mut c_void,
381        destroy: duckdb_delete_callback_t,
382    ) -> Self {
383        // SAFETY: forwarded from this method's own contract.
384        self.extra_info = Some(unsafe { crate::extra_info::ExtraInfo::new(ptr, destroy) });
385        self
386    }
387
388    /// Attaches `value` as this cast's extra info: the safe, typed form of
389    /// [`extra_info`][Self::extra_info].
390    ///
391    /// quack-rs boxes `value` behind a type tag and generates its destructor,
392    /// which contains a panic in `T::drop` and runs once — when `DuckDB`
393    /// releases the cast, or when this builder is dropped unregistered. Read
394    /// it in the callback with [`CastFunctionInfo::extra_info_ref`], which
395    /// returns `None` for any other type instead of reinterpreting memory.
396    /// `T` is `Send + Sync` because every thread running the cast reads the
397    /// same value.
398    ///
399    /// # Example
400    ///
401    /// ```rust,no_run
402    /// use quack_rs::cast::{CastFunctionBuilder, CastFunctionInfo};
403    /// use quack_rs::types::TypeId;
404    ///
405    /// struct Unit(&'static str);
406    ///
407    /// let builder =
408    ///     CastFunctionBuilder::new(TypeId::Double, TypeId::Varchar).extra_info_typed(Unit("kg"));
409    /// # drop(builder);
410    ///
411    /// fn unit(info: &CastFunctionInfo) -> &str {
412    ///     // SAFETY: this cast's extra info is only ever set with `extra_info_typed`.
413    ///     unsafe { info.extra_info_ref::<Unit>() }.map_or("", |u| u.0)
414    /// }
415    /// ```
416    pub fn extra_info_typed<T: Send + Sync + 'static>(self, value: T) -> Self {
417        let (data, destroy) = crate::extra_info::into_tagged(value);
418        // SAFETY: `into_tagged` returns a fresh allocation, used by no one
419        // else, and the destructor that frees it exactly once without
420        // unwinding; `T: Send + Sync`.
421        unsafe { self.extra_info(data, Some(destroy)) }
422    }
423
424    /// The completeness checks that need no `DuckDB` call: a function
425    /// callback, a source type and a target type.
426    /// [`MockRegistrar`][crate::testing::MockRegistrar] runs them too.
427    pub(crate) fn check_parts(&self) -> Result<(), ExtensionError> {
428        if self.function.is_none() {
429            return Err(ExtensionError::new("cast function callback not set"));
430        }
431        if self.source.is_none() && self.source_logical.is_none() {
432            return Err(ExtensionError::new("cast source type not set"));
433        }
434        if self.target.is_none() && self.target_logical.is_none() {
435            return Err(ExtensionError::new("cast target type not set"));
436        }
437        Ok(())
438    }
439
440    /// Refuses a type [`register`][Self::register] refuses before its first
441    /// `DuckDB` call; `slot` checks each `TypeId` (see [`SlotCheck`]).
442    pub(crate) fn check_types(&self, slot: SlotCheck) -> Result<(), ExtensionError> {
443        if let Some(id) = self.source {
444            slot(id, "cast function source type")?;
445        }
446        if let Some(id) = self.target {
447            slot(id, "cast function target type")?;
448        }
449        Ok(())
450    }
451
452    /// Registers the cast function on the given connection.
453    ///
454    /// # Errors
455    ///
456    /// Returns `ExtensionError` if:
457    /// - The function callback, source type or target type was not set.
458    /// - The source or target type is a bare composite [`TypeId`] (`DECIMAL`,
459    ///   `ENUM`, `LIST`, `STRUCT`, `MAP`, `ARRAY`, `UNION`); build it as a
460    ///   [`LogicalType`] and use [`new_logical`][Self::new_logical].
461    /// - `con` is null.
462    /// - The source or target type is, or contains, `ANY` or `INVALID`
463    ///   (`DuckDB` refuses these).
464    /// - `DuckDB` reports a registration failure.
465    ///
466    /// # `extra_info` ownership
467    ///
468    /// Every failure above is detected in Rust before `DuckDB` is called, so
469    /// the builder still owns any [`extra_info`][Self::extra_info] and frees
470    /// it (exactly once) when it is dropped. `duckdb_register_cast_function`
471    /// itself returns early for exactly those conditions *before* taking
472    /// ownership, which is why they are checked here first. The one remaining
473    /// failure — an exception inside `DuckDB` while installing the cast — is
474    /// ambiguous (it may or may not have taken ownership already), so the
475    /// allocation is left to `DuckDB` in that case: a possible leak, never a
476    /// double free.
477    ///
478    /// # Safety
479    ///
480    /// `con` must be a valid, open `duckdb_connection`.
481    pub unsafe fn register(self, con: duckdb_connection) -> Result<(), ExtensionError> {
482        // See `ScalarFunctionBuilder::register` -- validate before allocating.
483        // The checks that need no DuckDB call go first.
484        self.check_parts()?;
485        let function = self
486            .function
487            .ok_or_else(|| ExtensionError::new("cast function callback not set"))?;
488        self.check_types(LogicalType::check_slot)?;
489        if con.is_null() {
490            return Err(ExtensionError::new(
491                "cast function registration: connection is null",
492            ));
493        }
494
495        // Resolve source and target types: prefer explicit LogicalType over
496        // TypeId. Done before any DuckDB handle is created, so an early return
497        // leaks nothing.
498        let src_lt = if let Some(lt) = self.source_logical {
499            lt
500        } else if let Some(id) = self.source {
501            LogicalType::new(id)
502        } else {
503            return Err(ExtensionError::new("cast source type not set"));
504        };
505        let tgt_lt = if let Some(lt) = self.target_logical {
506            lt
507        } else if let Some(id) = self.target {
508            LogicalType::new(id)
509        } else {
510            return Err(ExtensionError::new("cast target type not set"));
511        };
512        for (lt, slot) in [(&src_lt, "source"), (&tgt_lt, "target")] {
513            // SAFETY: `lt` owns a live handle.
514            if unsafe { crate::table::type_check::contains_any_or_invalid(lt.as_raw()) } {
515                return Err(ExtensionError::new(format!(
516                    "cast function {slot} type must not be or contain ANY or INVALID; \
517                     DuckDB refuses to register such a cast"
518                )));
519            }
520        }
521
522        // SAFETY: allocates a new cast function handle.
523        let mut cast = unsafe { duckdb_create_cast_function() };
524
525        // SAFETY: cast and both type handles are valid; DuckDB copies the types.
526        unsafe {
527            duckdb_cast_function_set_source_type(cast, src_lt.as_raw());
528            duckdb_cast_function_set_target_type(cast, tgt_lt.as_raw());
529        }
530
531        // Set callback
532        // SAFETY: function is a valid extern "C" fn pointer.
533        unsafe {
534            duckdb_cast_function_set_function(cast, Some(function));
535        }
536
537        // Set implicit cost if requested
538        if let Some(cost) = self.implicit_cost {
539            // SAFETY: cast is a valid handle.
540            unsafe {
541                duckdb_cast_function_set_implicit_cast_cost(cast, cost);
542            }
543        }
544
545        // Attach extra info if provided
546        if let Some(info) = self.extra_info {
547            // SAFETY: ptr validity is the caller's responsibility per the safety
548            // contract on extra_info().
549            unsafe {
550                duckdb_cast_function_set_extra_info(cast, info.data(), info.destroy());
551            }
552            // Every deterministic pre-ownership rejection in
553            // `duckdb_register_cast_function` (null handles, missing parts,
554            // ANY/INVALID types) was ruled out above, so from here DuckDB owns
555            // the allocation — see "extra_info ownership" in the docs.
556            info.mark_transferred();
557        }
558
559        // Register
560        // SAFETY: con is a valid open connection, cast is fully configured.
561        let result = unsafe { duckdb_register_cast_function(con, cast) };
562
563        // SAFETY: cast was created above and must be destroyed after use.
564        unsafe {
565            duckdb_destroy_cast_function(&raw mut cast);
566        }
567
568        if result == DuckDBSuccess {
569            Ok(())
570        } else {
571            // Casts have no name to clash on, so the name-clash hint the other
572            // builders give does not apply.
573            Err(ExtensionError::new(
574                "duckdb_register_cast_function failed: the C API reports no reason, and every \
575                 cause quack-rs can detect (a missing function, an ANY or INVALID type) was \
576                 ruled out before the call",
577            ))
578        }
579    }
580}
581
582// ── Tests ──────────────────────────────────────────────────────────────────────
583
584crate::debug_repr::impl_handle_debug!(CastFunctionInfo.info);
585
586impl core::fmt::Debug for CastFunctionBuilder {
587    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
588        use crate::debug_repr::Callback;
589        f.debug_struct("CastFunctionBuilder")
590            .field("source", &self.source)
591            .field("source_logical", &self.source_logical)
592            .field("target", &self.target)
593            .field("target_logical", &self.target_logical)
594            .field("function", &Callback::of(&self.function))
595            .field("implicit_cost", &self.implicit_cost)
596            .field("extra_info", &Callback::of(&self.extra_info))
597            .finish()
598    }
599}
600
601#[cfg(test)]
602mod tests {
603    use super::*;
604    use libduckdb_sys::{duckdb_function_info, duckdb_vector, idx_t};
605
606    unsafe extern "C" fn noop_cast(
607        _: duckdb_function_info,
608        _: idx_t,
609        _: duckdb_vector,
610        _: duckdb_vector,
611    ) -> bool {
612        true
613    }
614
615    #[test]
616    fn builder_stores_source_and_target() {
617        let b = CastFunctionBuilder::new(TypeId::Varchar, TypeId::Integer);
618        assert_eq!(b.source(), Some(TypeId::Varchar));
619        assert_eq!(b.target(), Some(TypeId::Integer));
620    }
621
622    #[test]
623    fn builder_stores_function() {
624        let b = CastFunctionBuilder::new(TypeId::Varchar, TypeId::Integer).function(noop_cast);
625        assert!(b.function.is_some());
626    }
627
628    #[test]
629    fn builder_stores_implicit_cost() {
630        let b = CastFunctionBuilder::new(TypeId::Varchar, TypeId::Integer).implicit_cost(10);
631        assert_eq!(b.implicit_cost, Some(10));
632    }
633
634    #[test]
635    fn register_without_a_function_is_an_error_before_touching_duckdb() {
636        // The function check runs before any DuckDB call, so a null
637        // connection is never dereferenced.
638        // SAFETY: `register` returns before using `con`.
639        let err = unsafe {
640            CastFunctionBuilder::new(TypeId::BigInt, TypeId::Double).register(std::ptr::null_mut())
641        }
642        .expect_err("a builder without a function must be refused");
643        assert!(err.as_str().contains("callback not set"), "{err}");
644    }
645
646    #[test]
647    fn cast_mode_from_raw_normal() {
648        use libduckdb_sys::duckdb_cast_mode_DUCKDB_CAST_NORMAL;
649        assert_eq!(
650            CastMode::from_raw(duckdb_cast_mode_DUCKDB_CAST_NORMAL),
651            CastMode::Normal
652        );
653    }
654
655    #[test]
656    fn cast_mode_from_raw_try() {
657        assert_eq!(
658            CastMode::from_raw(duckdb_cast_mode_DUCKDB_CAST_TRY),
659            CastMode::Try
660        );
661    }
662
663    #[test]
664    fn cast_function_info_round_trips_its_handle() {
665        let raw = std::ptr::NonNull::<u8>::dangling().as_ptr().cast();
666        // SAFETY: the handle is only stored and read back, never passed to DuckDB.
667        let info = unsafe { CastFunctionInfo::new(raw) };
668        assert_eq!(info.info, raw);
669    }
670}