Skip to main content

quack_rs/cast/
mod.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 `DuckDB` custom cast functions.
7//!
8//! Cast functions let an extension define how to convert values from one type to
9//! another, covering both explicit `CAST(x AS T)` and implicit coercions that
10//! `DuckDB` may insert automatically.
11//!
12//! # How cast functions work
13//!
14//! ```text
15//! SELECT my_value::MyTargetType
16//!   ↓
17//! DuckDB looks up registered casts from source type → target type
18//!   ↓
19//! Calls your cast callback with:
20//!   - info:   duckdb_function_info  (use for extra data / error reporting)
21//!   - count:  idx_t                 (number of rows in this chunk)
22//!   - input:  duckdb_vector         (source values)
23//!   - output: duckdb_vector         (destination — write results here)
24//!   ↓
25//! Returns true when every row converted (see "TRY CAST vs normal CAST")
26//! ```
27//!
28//! # TRY CAST vs normal CAST
29//!
30//! [`CastFunctionInfo::cast_mode`] reports [`CastMode::Try`] whenever `DuckDB`
31//! asks for errors to be collected rather than thrown — for `TRY_CAST(x AS T)`,
32//! and also for the casts `DuckDB` applies to single values internally, such
33//! as converting a table function's argument to its declared parameter type
34//! (`Value::CastAs`). In this mode, call [`CastFunctionInfo::set_row_error`]
35//! for each row that fails to convert: it records the message **and** sets
36//! that row to `NULL`.
37//!
38//! **Return `false` whenever a row failed, in either mode.** In a normal
39//! `CAST`, `false` fails the query with the message you set. In a `TRY_CAST`,
40//! `DuckDB` ignores the return value
41//! (`src/execution/expression_executor/execute_cast.cpp`), so the rows you
42//! nulled are the answer — returning `false` does **not** null anything for
43//! you. In an internal value cast, `false` is the only signal: `DuckDB` throws
44//! `Failed to cast value: <your message>`, whereas `true` hands back a `NULL`
45//! silently. See [`CastFn`] for details; [`cast_callback!`][crate::cast_callback]
46//! nulls every row for you only when the body panics.
47//!
48//! # A cast replaces `DuckDB`'s own for that pair
49//!
50//! Registering a cast for a source/target pair `DuckDB` already converts —
51//! `VARCHAR → INTEGER`, say — **replaces the built-in conversion for the whole
52//! database**: every connection, `TRY_CAST`, and the implicit casts `DuckDB`
53//! inserts, such as the one an `INSERT` of a string into an `INTEGER` column
54//! performs.
55//!
56//! **The first registration for a pair wins.** Registering a cast for a pair
57//! that an extension has already registered — this one or another — succeeds
58//! and does nothing: `DuckDB` files casts in a `std::map` with `insert`, which
59//! never overwrites (`MapCastInfo::AddEntry`, `cast_function_set.cpp`), and
60//! frees the new registration's `extra_info` at once. Neither case is refused
61//! or reported, and the C API offers no way to ask whether a pair is already
62//! cast. Overriding is sometimes
63//! the point; when it is not, register casts to or from a type the extension
64//! owns (a named type from [`LogicalType::register`][crate::types::LogicalType::register]).
65//! `tests/ffi_roundtrip/table_cast.rs` pins both behaviours.
66//!
67//! # Example: register a VARCHAR → INTEGER cast
68//!
69//! This replaces the built-in `VARCHAR → INTEGER` cast (see above); it is here
70//! to show the callback's shape.
71//!
72//! ```rust,no_run
73//! use quack_rs::cast::{CastFunctionBuilder, CastFunctionInfo, CastMode};
74//! use quack_rs::types::TypeId;
75//! use quack_rs::vector::{VectorReader, VectorWriter};
76//! use libduckdb_sys::{duckdb_connection, duckdb_function_info, duckdb_vector, idx_t};
77//!
78//! unsafe extern "C" fn varchar_to_int(
79//!     info: duckdb_function_info,
80//!     count: idx_t,
81//!     input: duckdb_vector,
82//!     output: duckdb_vector,
83//! ) -> bool {
84//!     let cast_info = unsafe { CastFunctionInfo::new(info) };
85//!     let reader = unsafe { VectorReader::from_vector(input, count as usize) };
86//!     let mut writer = unsafe { VectorWriter::new(output) };
87//!
88//!     for row in 0..count as usize {
89//!         if !unsafe { reader.is_valid(row) } {
90//!             unsafe { writer.set_null(row) };
91//!             continue;
92//!         }
93//!         let s = unsafe { reader.read_str(row) };
94//!         match s.parse::<i32>() {
95//!             Ok(v) => unsafe { writer.write_i32(row, v) },
96//!             Err(e) => {
97//!                 if cast_info.cast_mode() == CastMode::Try {
98//!                     let msg = format!("cannot cast {:?} to INTEGER: {e}", s);
99//!                     unsafe { cast_info.set_row_error(&msg, row as idx_t, output) };
100//!                     unsafe { writer.set_null(row) };
101//!                 } else {
102//!                     let msg = format!("cannot cast {:?} to INTEGER: {e}", s);
103//!                     unsafe { cast_info.set_error(&msg) };
104//!                     return false;
105//!                 }
106//!             }
107//!         }
108//!     }
109//!     true
110//! }
111//!
112//! // fn register(con: duckdb_connection) -> Result<(), quack_rs::error::ExtensionError> {
113//! //     unsafe {
114//! //         CastFunctionBuilder::new(TypeId::Varchar, TypeId::Integer)
115//! //             .function(varchar_to_int)
116//! //             .register(con)
117//! //     }
118//! // }
119//! ```
120
121pub mod builder;
122
123pub use builder::{CastFn, CastFunctionBuilder, CastFunctionInfo, CastMode};