quack_rs/value/cast.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//! Casting a value to any logical type, and reading `ARRAY` and `UNION`
7//! values, whose contents the C API has no direct reader for.
8//!
9//! `duckdb_get_list_size` / `duckdb_get_list_child` read a `LIST` only and
10//! `duckdb_get_struct_child` a `STRUCT` only (`duckdb_value-c.cpp`, 1.4.4,
11//! 1.5.6 and 2.0.0 alike): an `ARRAY` reads as empty and a `UNION` as having
12//! no fields. A cast gets around both, and the cast here cannot throw through
13//! the C API: it is the one-element-`LIST` construction the scalar getters'
14//! `Value::cast_copy` uses, whose `duckdb_create_list_value` runs
15//! `Value::LIST` (and so `DefaultCastAs`) inside `try { } catch (...)` on all
16//! three releases.
17
18use libduckdb_sys::{
19 duckdb_array_type_child_type, duckdb_create_list_value, duckdb_get_list_child,
20 duckdb_get_value_type,
21};
22
23use super::temporal_checks::cast_guard;
24use super::Value;
25use crate::types::{LogicalType, TypeId};
26
27impl Value {
28 /// The value cast to `ty`, as a new owned handle, or `None` when `DuckDB`
29 /// refuses the cast. No checks of its own: every caller decides first
30 /// whether the payload is safe to cast.
31 ///
32 /// `Value::LIST(child_type, values)` casts each value with
33 /// `DefaultCastAs(child_type)`, which throws on a failed cast, and
34 /// `duckdb_create_list_value` catches the throw and returns null. The
35 /// child is then copied back out (`duckdb_get_list_child`).
36 // Every path past the null-handle check calls DuckDB, so a `--lib` mutation run
37 // with no engine cannot reach it; covered end to end in tests/ffi_roundtrip.
38 #[cfg_attr(test, mutants::skip)]
39 pub(super) fn cast_into(&self, ty: &LogicalType) -> Option<Self> {
40 if self.raw.is_null() {
41 return None;
42 }
43 let mut child = self.raw;
44 // SAFETY: `ty` is a live type owned by the caller; `child` points to
45 // exactly one live handle, matching `value_count == 1`. DuckDB copies
46 // and casts it, and catches every exception the cast throws.
47 let list = unsafe { duckdb_create_list_value(ty.as_raw(), &raw mut child, 1) };
48 // SAFETY: `list` is null (never dereferenced by `Value`) or an owned
49 // handle returned by DuckDB.
50 let list = unsafe { Self::from_raw(list) };
51 if list.is_null() {
52 return None;
53 }
54 // SAFETY: `list` is a live, non-NULL `LIST` with one child.
55 let copy = unsafe { duckdb_get_list_child(list.raw, 0) };
56 // SAFETY: `copy` is null or a new owned handle.
57 let copy = unsafe { Self::from_raw(copy) };
58 (!copy.is_null()).then_some(copy)
59 }
60
61 /// Casts the value to `target`, as SQL's `TRY_CAST(value AS target)`
62 /// does, and returns the result as a new owned value; `None` when the cast
63 /// fails.
64 ///
65 /// This is the general form of the casting `as_*` getters, for any
66 /// [`LogicalType`] — nested ones included — and the way to read the
67 /// values the C API has no reader for:
68 ///
69 /// - an `ARRAY` cast to a `LIST` of its element type reads with
70 /// [`list_items`][Self::list_items] (or use
71 /// [`array_items`][Self::array_items], which does exactly that);
72 /// - a `UNION` cast to `VARCHAR` is its active member as text
73 /// (`DuckDB` casts a `UNION` only to `VARCHAR` or to another `UNION`);
74 /// `Value::union_tag` (feature `duckdb-1-5`) says which member it is;
75 /// - a `VARCHAR` cast to `LIST(INTEGER)`, `STRUCT(..)` or `DATE` parses
76 /// it the way SQL does.
77 ///
78 /// A SQL `NULL` casts to a `NULL` of the target type (`Some`), as in SQL.
79 /// `self` is never modified.
80 ///
81 /// Returns `None` when the handle is null, the cast fails (`'abc'` to
82 /// `INTEGER`, a `LIST` to `INTEGER`, an `ARRAY` to a `LIST` of the wrong
83 /// size), `target` is `ANY` / `INVALID` or a type quack-rs does not
84 /// know, or the value holds a payload `DuckDB` cannot convert safely: the
85 /// same timestamp, time and `DECIMAL` payloads
86 /// [`as_str`][Self::as_str] refuses to render (see
87 /// [`UNRENDERABLE`][super::UNRENDERABLE]), anywhere inside the value.
88 /// Those payloads do not come from SQL's own constructors, but from
89 /// functions such as `make_timestamp(-9223372036854775808)`; converting
90 /// one throws, or overflows a signed multiply, inside `DuckDB`. A `UNION`
91 /// whose member types include a timestamp, time or `DECIMAL` is refused
92 /// whatever its member holds, because the member cannot be read to check
93 /// it first.
94 ///
95 /// Works on every supported `DuckDB` (1.4.4 to 2.0.x): it uses only
96 /// stable C API calls.
97 ///
98 /// # Example
99 ///
100 /// Reading an `INTEGER[3]` parameter of a table function (needs a live
101 /// engine, so it is not run here):
102 ///
103 /// ```rust,no_run
104 /// use quack_rs::types::{LogicalType, TypeId};
105 /// use quack_rs::value::Value;
106 ///
107 /// # fn demo(param: &Value) -> Option<Vec<i32>> {
108 /// let as_list = param.try_cast(&LogicalType::list(TypeId::Integer))?;
109 /// as_list.list_items().iter().map(Value::as_i32).collect()
110 /// # }
111 /// ```
112 // Every path past the null-handle check calls DuckDB, so a `--lib` mutation run
113 // with no engine cannot reach it; covered end to end in tests/ffi_roundtrip.
114 #[cfg_attr(test, mutants::skip)]
115 #[must_use]
116 pub fn try_cast(&self, target: &LogicalType) -> Option<Self> {
117 if self.raw.is_null() {
118 return None;
119 }
120 // SAFETY: `target` is a live handle (a `LogicalType` invariant), and
121 // a non-null `Value` means the C API is initialised.
122 let target_id = unsafe { target.try_get_type_id() }?;
123 if !self.is_sql_null() && !self.payload_casts_safely(target_id) {
124 return None;
125 }
126 let copy = self.cast_into(target)?;
127 (copy.type_id() == Some(target_id)).then_some(copy)
128 }
129
130 /// Whether every payload inside this (non-NULL) value is one `DuckDB`
131 /// converts without throwing through the C API or overflowing: the
132 /// `renderable` check (`render_guard.rs`), element by element, with an
133 /// `ARRAY` first turned into a `LIST` of its own element type so that its
134 /// elements can be checked too. Then, as in the scalar getters, a
135 /// timestamp-to-time pair `DuckDB` converts with a throwing loop is
136 /// checked against the exact condition it fails on.
137 // Every path past the null-handle check calls DuckDB, so a `--lib` mutation run
138 // with no engine cannot reach it; covered end to end in tests/ffi_roundtrip.
139 #[cfg_attr(test, mutants::skip)]
140 fn payload_casts_safely(&self, target: TypeId) -> bool {
141 let Some(source) = self.type_id() else {
142 return false;
143 };
144 let checked = if source == TypeId::Array {
145 self.array_as_list().is_some_and(|list| list.renderable())
146 } else {
147 self.renderable()
148 };
149 if !checked {
150 return false;
151 }
152 cast_guard(source, target).is_none_or(|guard| {
153 self.temporal_payload(source)
154 .is_some_and(|v| guard.accepts(v))
155 })
156 }
157
158 /// An `ARRAY` value cast to a `LIST` of its own element type; `None` for
159 /// any other value.
160 ///
161 /// The cast cannot convert an element: `ArrayToListCast` binds its
162 /// element cast with `GetCastFunction(child, child)`, which is `NopCast`
163 /// when the two types are equal (`cast_function_set.cpp`, 1.4.4, 1.5.6
164 /// and 2.0.0), so no element payload is read. That is what lets
165 /// [`try_cast`][Self::try_cast] check the elements before a real cast.
166 // Every path past the null-handle check calls DuckDB, so a `--lib` mutation run
167 // with no engine cannot reach it; covered end to end in tests/ffi_roundtrip.
168 #[cfg_attr(test, mutants::skip)]
169 fn array_as_list(&self) -> Option<Self> {
170 if self.type_id() != Some(TypeId::Array) {
171 return None;
172 }
173 // SAFETY: `self.raw` is a live, non-null value (`type_id` returned
174 // `Some`). The type is owned by the value and is only read here.
175 let array_type = unsafe { duckdb_get_value_type(self.raw) };
176 // SAFETY: `array_type` is a live `ARRAY` type. DuckDB returns a new
177 // type the caller owns, or null.
178 let element = unsafe { duckdb_array_type_child_type(array_type) };
179 if element.is_null() {
180 return None;
181 }
182 // SAFETY: `element` is a non-null, owned handle; `LogicalType`
183 // destroys it on drop.
184 let element = unsafe { LogicalType::from_raw(element) };
185 let list_type = LogicalType::try_list_from_logical(&element).ok()?;
186 self.cast_into(&list_type)
187 }
188
189 /// The elements of an `ARRAY` (or a `LIST`) value, in order; `None` for
190 /// a null handle, a SQL `NULL` or a value of any other type.
191 ///
192 /// [`list_items`][Self::list_items] reads a `LIST` only, and an `ARRAY`
193 /// value read through it looks empty: the C API has no `ARRAY` reader.
194 /// This casts an `ARRAY(T, n)` to `LIST(T)` first — a cast that copies
195 /// the elements unchanged — so a fixed-size-list parameter of a table
196 /// function, a `COPY` option or a scalar bind argument can be read.
197 /// Each element is an owned [`Value`] of type `T`, read with the usual
198 /// getters.
199 ///
200 /// Works on every supported `DuckDB` (1.4.4 to 2.0.x).
201 ///
202 /// # Example
203 ///
204 /// ```rust,no_run
205 /// use quack_rs::value::Value;
206 ///
207 /// # fn demo(point: &Value) -> Option<(f64, f64)> {
208 /// // A `DOUBLE[2]` parameter.
209 /// let items = point.array_items()?;
210 /// Some((items.first()?.as_f64()?, items.get(1)?.as_f64()?))
211 /// # }
212 /// ```
213 // Every path past the null-handle check calls DuckDB, so a `--lib` mutation run
214 // with no engine cannot reach it; covered end to end in tests/ffi_roundtrip.
215 #[cfg_attr(test, mutants::skip)]
216 #[must_use]
217 pub fn array_items(&self) -> Option<Vec<Self>> {
218 if self.is_sql_null() {
219 return None;
220 }
221 match self.type_id()? {
222 TypeId::List => Some(self.list_items()),
223 TypeId::Array => Some(self.array_as_list()?.list_items()),
224 _ => None,
225 }
226 }
227}
228
229#[cfg(feature = "duckdb-1-5")]
230impl Value {
231 /// The tag of a `UNION` value: the 0-based index of its active member,
232 /// in the order the `UNION` type declares them (`DuckDB` 1.5.0+).
233 ///
234 /// Returns `None` for a null handle, a SQL `NULL` and any value that is
235 /// not a `UNION`.
236 ///
237 /// The member's name is entry `tag + 1` of
238 /// [`struct_field_names`][Self::struct_field_names] (a `UNION` lists its
239 /// hidden tag field first). Its value reads as text
240 /// with [`try_cast`][Self::try_cast] to `VARCHAR`, the only scalar type
241 /// `DuckDB` casts a `UNION` to; a member whose value is `NULL` reads as
242 /// the text `"NULL"` there (`UnionToVarcharCast`), which cannot be told
243 /// apart from a `VARCHAR` member holding that text.
244 ///
245 /// # How
246 ///
247 /// The C API reads a `UNION` value's tag nowhere: `duckdb_get_struct_child`
248 /// refuses a `UNION`, and no cast yields the tag. A `UNION` is stored as a
249 /// `STRUCT` whose field 0 is the `UTINYINT` tag, so this references the
250 /// value into a one-row vector of its own type
251 /// (`duckdb_vector_reference_value`) and reads field 0 there. Requires
252 /// `duckdb-1-5`: `duckdb_create_vector` and
253 /// `duckdb_vector_reference_value` sit in the unstable region of the C API
254 /// struct.
255 ///
256 /// # Example
257 ///
258 /// ```rust,no_run
259 /// use quack_rs::types::{LogicalType, TypeId};
260 /// use quack_rs::value::Value;
261 ///
262 /// # fn demo(arg: &Value) -> Option<String> {
263 /// // A `UNION(num INTEGER, str VARCHAR)` parameter.
264 /// let tag = arg.union_tag()?;
265 /// let member = arg.struct_field_names().get(usize::from(tag) + 1)?.clone();
266 /// let text = arg.try_cast(&LogicalType::new(TypeId::Varchar))?.as_str().ok()?;
267 /// Some(format!("{member} = {text}"))
268 /// # }
269 /// ```
270 // Every path past the null-handle check calls DuckDB, so a `--lib` mutation run
271 // with no engine cannot reach it; covered end to end in tests/ffi_roundtrip.
272 #[cfg_attr(test, mutants::skip)]
273 #[must_use]
274 pub fn union_tag(&self) -> Option<u8> {
275 /// Destroys a vector `duckdb_create_vector` returned.
276 struct OwnedVector(libduckdb_sys::duckdb_vector);
277 impl Drop for OwnedVector {
278 fn drop(&mut self) {
279 // SAFETY: `self.0` came from `duckdb_create_vector`, is
280 // non-null, and is destroyed exactly once, here.
281 unsafe { libduckdb_sys::duckdb_destroy_vector(&raw mut self.0) };
282 }
283 }
284
285 if self.is_sql_null() || self.type_id() != Some(TypeId::Union) {
286 return None;
287 }
288 // SAFETY: `self.raw` is a live, non-null `UNION` value; its type is
289 // owned by the value and only read (copied) below.
290 let union_type = unsafe { duckdb_get_value_type(self.raw) };
291 // SAFETY: `union_type` is live; `duckdb_create_vector` copies it and
292 // catches every exception, returning null on failure.
293 let vector = unsafe { libduckdb_sys::duckdb_create_vector(union_type, 1) };
294 if vector.is_null() {
295 return None;
296 }
297 let vector = OwnedVector(vector);
298 // SAFETY: the vector was created from this value's own type, which is
299 // what `Vector::Reference(const Value &)` requires (it asserts the
300 // type ids match and lays the value out by the vector's type); the
301 // value is non-NULL, so every field, the tag included, is written at
302 // row 0.
303 unsafe { libduckdb_sys::duckdb_vector_reference_value(vector.0, self.raw) };
304 // SAFETY: a `UNION` vector is a `STRUCT` vector whose child 0 is the
305 // tag; index 0 exists for every `UNION` type.
306 let tags = unsafe { libduckdb_sys::duckdb_struct_vector_get_child(vector.0, 0) };
307 if tags.is_null() {
308 return None;
309 }
310 // SAFETY: `tags` is a flat or constant `UTINYINT` vector owned by
311 // `vector`, which is still alive.
312 let data = unsafe { libduckdb_sys::duckdb_vector_get_data(tags) }.cast::<u8>();
313 if data.is_null() {
314 return None;
315 }
316 // SAFETY: row 0 of a one-row `UTINYINT` vector, written by
317 // `duckdb_vector_reference_value` above.
318 Some(unsafe { *data })
319 }
320}