quack_rs/value.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//! RAII wrapper around `DuckDB` values (`duckdb_value`).
7//!
8//! [`Value`] provides safe, typed access to `DuckDB` values returned from bind
9//! parameter extraction, configuration options, and other APIs. It automatically
10//! calls [`duckdb_destroy_value`] on drop, eliminating the manual cleanup that
11//! every extension author currently has to remember.
12//!
13//! # Example
14//!
15//! ```rust,no_run
16//! use quack_rs::value::Value;
17//! use quack_rs::table::BindInfo;
18//! use libduckdb_sys::duckdb_bind_info;
19//!
20//! unsafe extern "C" fn my_bind(info: duckdb_bind_info) {
21//! let bind = unsafe { BindInfo::new(info) };
22//! // RAII: Value is destroyed automatically when it goes out of scope.
23//! let val = unsafe { Value::from_raw(bind.get_parameter(0)) };
24//! if let Ok(s) = val.as_str() {
25//! // use s...
26//! }
27//! }
28//! ```
29
30mod bits;
31mod blob;
32mod cast;
33mod checks;
34mod composite;
35mod defaults;
36mod getters;
37mod hugeint;
38mod nested;
39mod render_guard;
40mod scalars;
41mod temporal;
42pub(crate) mod temporal_checks;
43
44pub(crate) use checks::validate_decimal;
45
46// Re-exported unqualified so the eight call sites across this module and
47// `query` keep their existing `crate::value::hugeint_from_i128` paths.
48pub(crate) use hugeint::{
49 hugeint_from_i128, hugeint_to_i128, uhugeint_from_u128, uhugeint_to_u128,
50};
51
52use std::ffi::CStr;
53use std::os::raw::c_char;
54
55#[cfg(feature = "duckdb-1-5")]
56use libduckdb_sys::duckdb_value_to_string;
57use libduckdb_sys::{duckdb_destroy_value, duckdb_free, duckdb_get_varchar, duckdb_value};
58
59use crate::error::ExtensionError;
60
61/// An owned, RAII-managed `DuckDB` value.
62///
63/// When dropped, the underlying `duckdb_value` handle is destroyed via
64/// [`duckdb_destroy_value`]. This eliminates the manual `duckdb_destroy_value`
65/// calls that are easy to forget and lead to memory leaks.
66///
67/// # Creation
68///
69/// Obtain a `Value` from:
70/// - [`BindInfo::get_parameter_value`][crate::table::BindInfo::get_parameter_value]
71/// - [`BindInfo::get_named_parameter_value`][crate::table::BindInfo::get_named_parameter_value]
72/// - [`Value::from_raw`] (escape hatch for raw `duckdb_value` handles)
73///
74/// # Extraction
75///
76/// Use typed accessors to extract the underlying data:
77/// - [`as_str`][Value::as_str] — any scalar rendered as text → `Result<String>`
78/// - [`as_blob`][Value::as_blob] — BLOB → `Result<Vec<u8>>`
79/// - [`as_i32`][Value::as_i32] — cast to INTEGER → `Option<i32>`
80/// - [`as_i64`][Value::as_i64] — cast to BIGINT → `Option<i64>`
81/// - [`as_f32`][Value::as_f32] — cast to FLOAT → `Option<f32>`
82/// - [`as_f64`][Value::as_f64] — cast to DOUBLE → `Option<f64>`
83/// - [`as_bool`][Value::as_bool] — cast to BOOLEAN → `Option<bool>`
84/// - [`as_bit`][Value::as_bit] / [`as_bignum`][Value::as_bignum] — BIT and
85/// BIGNUM, which the C getters would abort the process on for a `NULL`
86/// - [`try_cast`][Value::try_cast] — cast to any [`LogicalType`][crate::types::LogicalType],
87/// nested ones included; [`array_items`][Value::array_items] reads an
88/// `ARRAY`, which [`list_items`][Value::list_items] cannot
89///
90/// No accessor calls into `DuckDB` for a null handle or a SQL `NULL` — the
91/// scalar getters return `None`, `as_str`/`as_blob` an error — and none
92/// modifies the value. The `as_*_or(default)` forms (e.g.
93/// [`as_i64_or`][Value::as_i64_or]) fold every `None` into a default.
94pub struct Value {
95 raw: duckdb_value,
96}
97
98impl Value {
99 /// Wraps a raw `duckdb_value` handle.
100 ///
101 /// The returned `Value` takes ownership and will call `duckdb_destroy_value`
102 /// on drop.
103 ///
104 /// # Safety
105 ///
106 /// `raw` must be a valid `duckdb_value` obtained from a `DuckDB` API call
107 /// (e.g., `duckdb_bind_get_parameter`). The caller must not destroy the
108 /// value after passing it to this function.
109 #[inline]
110 #[must_use]
111 pub const unsafe fn from_raw(raw: duckdb_value) -> Self {
112 Self { raw }
113 }
114
115 /// Extracts the value as a `String` (VARCHAR).
116 ///
117 /// Internally calls `duckdb_get_varchar` and frees the returned C string
118 /// with `duckdb_free`. Returns an error if the string is not valid UTF-8
119 /// or if the value handle is null.
120 ///
121 /// # Embedded NUL bytes
122 ///
123 /// `duckdb_get_varchar` returns a NUL-terminated `char *`, so a value whose
124 /// text contains an interior NUL is **truncated at the first one**. `DuckDB`
125 /// itself stores the full bytes; only this read path is limited. If the text
126 /// may contain NULs, keep it in a `BLOB` and use
127 /// [`as_blob`][Self::as_blob].
128 ///
129 /// # A `UNION` renders as its member
130 ///
131 /// The text is the value cast to `VARCHAR`, as SQL casts it, so a `UNION`
132 /// renders as its active member alone: `union_value(a := 5)` as `"5"`,
133 /// with the tag gone, and a `UNION` whose member is `NULL` as the text
134 /// `"NULL"` — returned as text, not as an error, because the `UNION`
135 /// itself is not SQL `NULL`. The `Debug` form keeps the tag.
136 ///
137 /// # Errors
138 ///
139 /// Returns `ExtensionError` if the handle is null, the value is SQL `NULL`
140 /// (`duckdb_get_varchar` would throw on it, aborting the process), the
141 /// text is not valid UTF-8, or the value holds something `DuckDB` cannot
142 /// render — see [`UNRENDERABLE`]. `DuckDB` builds such values from
143 /// ordinary SQL (`make_timestamp(-9223372036854775808)`, or, before 2.0,
144 /// `sum` over a `DECIMAL(38, s)` column), and rendering one throws through the C API,
145 /// which aborted the process.
146 pub fn as_str(&self) -> Result<String, ExtensionError> {
147 if self.raw.is_null() {
148 return Err(ExtensionError::new("Value is null"));
149 }
150 if self.is_sql_null() {
151 return Err(ExtensionError::new("Value is SQL NULL"));
152 }
153 if !self.renderable() {
154 return Err(ExtensionError::new(UNRENDERABLE));
155 }
156 // SAFETY: self.raw is a valid duckdb_value per constructor contract.
157 let c_str: *mut c_char = unsafe { duckdb_get_varchar(self.raw) };
158 if c_str.is_null() {
159 return Err(ExtensionError::new("duckdb_get_varchar returned null"));
160 }
161 // SAFETY: c_str is a valid null-terminated C string allocated by DuckDB.
162 let result = unsafe { CStr::from_ptr(c_str) }
163 .to_str()
164 .map(str::to_owned)
165 .map_err(|_| ExtensionError::new("Value contains invalid UTF-8"));
166 // SAFETY: c_str was allocated by DuckDB and must be freed with duckdb_free.
167 unsafe { duckdb_free(c_str.cast()) };
168 result
169 }
170
171 /// Returns the **SQL literal** representation of this value, as `DuckDB`
172 /// would render it (`DuckDB` 1.5.0+).
173 ///
174 /// Note "SQL literal", not "text". A VARCHAR comes back quoted and typed
175 /// values carry an explicit cast:
176 ///
177 /// | Value | `display_string()` |
178 /// |-------|--------------------|
179 /// | `Value::varchar("hello")` | `'hello'` |
180 /// | `Value::bigint(-42)` | `-42` |
181 /// | `Value::date(0)` | `'1970-01-01'::DATE` |
182 /// | `Value::timestamp(0)` | `'1970-01-01 00:00:00'::TIMESTAMP` |
183 ///
184 /// The exact text is `DuckDB`'s `Value::ToSQLString`, which changes
185 /// between releases. From 2.0.0 a typed `NULL` and a nested value carry
186 /// their type as well: a `UNION` whose member is `NULL` renders as
187 /// `union_value(a := NULL::INTEGER)::UNION(a INTEGER)`, where 1.x
188 /// rendered `union_value(a := NULL)`.
189 ///
190 /// Use [`as_str`][Self::as_str] for a VARCHAR's contents. This is for
191 /// diagnostics and error messages, where it works for any value type.
192 ///
193 /// Returns `None` if the handle is null, the rendered text is not valid
194 /// UTF-8, or the value is one `DuckDB` cannot render (see
195 /// [`UNRENDERABLE`]).
196 #[cfg(feature = "duckdb-1-5")]
197 #[must_use]
198 pub fn display_string(&self) -> Option<String> {
199 if self.raw.is_null() || !self.renderable() {
200 return None;
201 }
202 // SAFETY: self.raw is a valid duckdb_value per constructor contract.
203 let c_str: *mut c_char = unsafe { duckdb_value_to_string(self.raw) };
204 if c_str.is_null() {
205 return None;
206 }
207 // SAFETY: c_str is a valid null-terminated string allocated by DuckDB.
208 let result = unsafe { CStr::from_ptr(c_str) }
209 .to_str()
210 .ok()
211 .map(str::to_owned);
212 // SAFETY: c_str was allocated by DuckDB and must be freed with duckdb_free.
213 unsafe { duckdb_free(c_str.cast()) };
214 result
215 }
216
217 /// Returns `true` when this value's SQL type is `SQLNULL`.
218 ///
219 /// This is **not** [`is_null`][Self::is_null], which reports whether the
220 /// *handle* is null — a value that failed to construct, or one moved out
221 /// with [`into_raw`][Self::into_raw]. A SQL `NULL` has a perfectly valid
222 /// handle.
223 ///
224 /// # Example
225 ///
226 /// ```rust,no_run
227 /// use quack_rs::value::Value;
228 ///
229 /// let v = Value::null_value();
230 /// assert!(!v.is_null(), "the handle is fine");
231 /// assert!(v.is_sql_null(), "the value is SQL NULL");
232 /// ```
233 #[must_use]
234 pub fn is_sql_null(&self) -> bool {
235 if self.raw.is_null() {
236 return false;
237 }
238 // SAFETY: `self.raw` is a valid duckdb_value per the constructor contract.
239 unsafe { libduckdb_sys::duckdb_is_null_value(self.raw) }
240 }
241
242 /// Returns the [`TypeId`][crate::types::TypeId] this value actually holds.
243 ///
244 /// The casting `as_*` accessors follow SQL's `TRY_CAST` — a `VARCHAR`
245 /// `'42'` reads as `42` through [`as_i64`][Self::as_i64]. Check the type
246 /// first when a value whose type you did not choose — a named parameter,
247 /// a bound constant, a config option — must be of one particular type.
248 ///
249 /// Returns `None` for a null handle, and for a type id introduced by a
250 /// newer `DuckDB` than this build of quack-rs knows.
251 ///
252 /// # Example
253 ///
254 /// ```rust,no_run
255 /// use quack_rs::types::TypeId;
256 /// use quack_rs::value::Value;
257 ///
258 /// # fn demo(value: &Value) -> Option<i64> {
259 /// match value.type_id()? {
260 /// TypeId::BigInt | TypeId::Integer => value.as_i64(),
261 /// _ => None,
262 /// }
263 /// # }
264 /// ```
265 #[must_use]
266 pub fn type_id(&self) -> Option<crate::types::TypeId> {
267 if self.raw.is_null() {
268 return None;
269 }
270 // SAFETY: `self.raw` is a valid duckdb_value per the constructor
271 // contract. The returned logical type is owned by the value — duckdb.h
272 // states "The type itself must not be destroyed" — so it is read
273 // directly rather than wrapped in `LogicalType`, which frees on drop.
274 let logical = unsafe { libduckdb_sys::duckdb_get_value_type(self.raw) };
275 if logical.is_null() {
276 return None;
277 }
278 // SAFETY: `logical` is non-null and valid for as long as `self` is.
279 let raw_id = unsafe { libduckdb_sys::duckdb_get_type_id(logical) };
280 crate::types::TypeId::try_from_duckdb_type(raw_id)
281 }
282
283 /// Returns `true` if the underlying **handle** is null — not whether the
284 /// value is SQL `NULL`.
285 ///
286 /// A SQL `NULL` (for example a `NULL` passed to a table function's
287 /// parameter) has a valid handle, so this returns `false` for it. To test
288 /// for SQL `NULL`, use [`is_sql_null`][Self::is_sql_null].
289 #[inline]
290 #[must_use]
291 pub const fn is_null(&self) -> bool {
292 self.raw.is_null()
293 }
294
295 /// Returns the raw `duckdb_value` handle without consuming the `Value`.
296 ///
297 /// The `Value` still owns the handle and will destroy it on drop.
298 #[inline]
299 #[must_use]
300 pub const fn as_raw(&self) -> duckdb_value {
301 self.raw
302 }
303
304 /// Consumes the `Value` and returns the raw `duckdb_value` handle.
305 ///
306 /// The caller takes ownership and is responsible for calling
307 /// `duckdb_destroy_value` when done.
308 #[inline]
309 #[must_use]
310 pub const fn into_raw(self) -> duckdb_value {
311 let raw = self.raw;
312 std::mem::forget(self);
313 raw
314 }
315}
316
317/// What [`Value::as_str`] reports for a value `DuckDB` cannot render.
318///
319/// That is a value holding a timestamp or time payload outside the range
320/// `DuckDB` converts, a `DECIMAL` wider than its type, a `VARIANT`, a
321/// `GEOMETRY` or a type quack-rs does not know, or an `ARRAY` / `UNION` that
322/// could hold one, whose elements the C API gives no way to check first; or a
323/// `BIT` whose bytes are malformed, which only the raw `duckdb_create_bit`
324/// builds.
325pub const UNRENDERABLE: &str = "Value cannot be rendered: it holds a timestamp or time payload \
326 outside the range DuckDB converts, a DECIMAL wider than its type, a VARIANT, a GEOMETRY, a \
327 malformed BIT or a type quack-rs does not know (or an ARRAY / UNION that could hold one, \
328 which cannot be checked), and DuckDB's rendering would throw through the C API and abort \
329 the process";
330
331impl Drop for Value {
332 fn drop(&mut self) {
333 if !self.raw.is_null() {
334 // SAFETY: self.raw is a valid duckdb_value that we own.
335 unsafe { duckdb_destroy_value(&raw mut self.raw) };
336 }
337 }
338}
339
340impl core::fmt::Debug for Value {
341 /// Prints the value's type and, where `DuckDB` can render it, its contents.
342 ///
343 /// Like [`LogicalType`][crate::types::LogicalType]'s impl this calls into
344 /// `DuckDB`, so it avoids every path that could panic while formatting.
345 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
346 if self.raw.is_null() {
347 return f.write_str("Value(<null handle>)");
348 }
349 let mut out = f.debug_struct("Value");
350 match self.type_id() {
351 Some(type_id) => out.field("type", &type_id),
352 None => out.field("type", &"<unknown>"),
353 };
354 #[cfg(feature = "duckdb-1-5")]
355 if let Some(rendered) = self.display_string() {
356 out.field("value", &rendered);
357 }
358 out.finish()
359 }
360}
361
362#[cfg(test)]
363mod tests {
364 use super::*;
365
366 #[test]
367 fn null_value_is_null() {
368 let val = unsafe { Value::from_raw(std::ptr::null_mut()) };
369 assert!(val.is_null());
370 }
371
372 #[test]
373 fn null_value_as_str_returns_error() {
374 let val = unsafe { Value::from_raw(std::ptr::null_mut()) };
375 assert!(val.as_str().is_err());
376 }
377
378 #[test]
379 fn into_raw_prevents_double_free() {
380 let val = unsafe { Value::from_raw(std::ptr::null_mut()) };
381 let raw = val.into_raw();
382 assert!(raw.is_null());
383 // No double-free: Value was forgotten via into_raw.
384 }
385
386 #[test]
387 fn size_of_value() {
388 assert_eq!(std::mem::size_of::<Value>(), std::mem::size_of::<usize>());
389 }
390}
391
392/// `Value` accessors exercised against a live `DuckDB`.
393///
394/// These go through real `duckdb_value` handles produced by SQL, which is the
395/// only way to be sure each `duckdb_get_*` is paired with the right SQL type.
396#[cfg(all(test, feature = "_duckdb-testing"))]
397mod live_tests {
398 use super::Value;
399 use crate::datetime;
400 use crate::testing::InMemoryDb;
401
402 /// Evaluates `expr` and returns the result as an owned `Value`.
403 ///
404 /// Uses `duckdb_create_*` round-tripping through SQL is not possible from
405 /// the C API, so this builds the value with the constructors under test and
406 /// checks it against `DuckDB`'s own rendering.
407 #[cfg(feature = "duckdb-1-5")]
408 fn rendered(value: &Value) -> String {
409 value
410 .display_string()
411 .expect("DuckDB should render every value")
412 }
413
414 /// `display_string` wraps `duckdb_value_to_string`, which lives past the
415 /// stable prefix, so this assertion set needs `duckdb-1-5`.
416 #[cfg(feature = "duckdb-1-5")]
417 #[test]
418 fn scalar_constructors_render_as_duckdb_would() {
419 let _db = InMemoryDb::open().expect("open in-memory DuckDB");
420 assert_eq!(rendered(&Value::boolean(true)), "true");
421 assert_eq!(rendered(&Value::bigint(-42)), "-42");
422 // `duckdb_value_to_string` renders a SQL *literal*, so a VARCHAR is
423 // quoted. This is easy to trip over when using it for diagnostics.
424 assert_eq!(rendered(&Value::varchar("hello")), "'hello'");
425 // Typed values carry an explicit cast, which is what makes this a SQL
426 // *literal* rather than a display string.
427 assert_eq!(rendered(&Value::date(0)), "'1970-01-01'::DATE");
428 assert_eq!(
429 rendered(&Value::timestamp(0).expect("in range")),
430 "'1970-01-01 00:00:00'::TIMESTAMP"
431 );
432 assert!(Value::null_value().display_string().is_some());
433 }
434
435 #[test]
436 fn temporal_constructors_round_trip_through_accessors() {
437 let _db = InMemoryDb::open().expect("open in-memory DuckDB");
438
439 // 2026-08-18 is 20685 days after the epoch; check against the calendar
440 // conversion rather than restating the number.
441 // SAFETY: InMemoryDb::open() initialised the dispatch table.
442 let days = unsafe {
443 datetime::date_to_days(datetime::Date {
444 year: 2026,
445 month: 8,
446 day: 18,
447 })
448 }
449 .expect("2026-08-18 is a valid date");
450 assert_eq!(Value::date(days).as_date(), Some(days));
451
452 let micros = 1_700_000_000_000_000_i64;
453 assert_eq!(
454 Value::timestamp(micros).expect("in range").as_timestamp(),
455 Some(micros)
456 );
457 assert_eq!(Value::bigint(i64::MIN).as_i64(), Some(i64::MIN));
458 assert_eq!(Value::bigint(i64::MAX).as_i64(), Some(i64::MAX));
459 }
460
461 #[test]
462 fn as_str_truncates_at_an_embedded_nul() {
463 let _db = InMemoryDb::open().expect("open in-memory DuckDB");
464 // `duckdb_create_varchar_length` stores all three bytes, but
465 // `duckdb_get_varchar` hands back a NUL-terminated C string, so the read
466 // path truncates. Pinned so the documented caveat stays accurate.
467 let value = Value::varchar("a\0b");
468 assert_eq!(value.as_str().expect("utf8"), "a");
469 }
470
471 #[test]
472 fn uuid_round_trips_including_the_high_bit() {
473 let _db = InMemoryDb::open().expect("open in-memory DuckDB");
474 // `duckdb_get_uuid` returns an *unsigned* hugeint. Assembling its halves
475 // directly as i128 overflows once the upper half's high bit is set —
476 // which is true for half of all UUIDs, and panics in a debug build.
477 for bits in [0_u128, 1, u128::MAX, 1 << 127, (1 << 127) - 1] {
478 assert_eq!(
479 Value::uuid(bits).as_uuid(),
480 Some(bits),
481 "round trip for {bits:#034x}"
482 );
483 }
484 }
485
486 #[test]
487 fn list_and_map_accessors_bounds_check() {
488 let _db = InMemoryDb::open().expect("open in-memory DuckDB");
489 // A scalar is not a list; the accessors must report that rather than
490 // reading out of range.
491 let scalar = Value::bigint(1);
492 assert_eq!(scalar.list_len(), 0);
493 assert!(scalar.list_child(0).is_none());
494 assert_eq!(scalar.map_len(), 0);
495 assert!(scalar.map_key(0).is_none());
496 assert!(scalar.map_value(0).is_none());
497 }
498
499 #[test]
500 fn accessors_on_a_null_handle_do_not_crash() {
501 let _db = InMemoryDb::open().expect("open in-memory DuckDB");
502 // SAFETY: a null handle is explicitly part of `Value`'s contract — it is
503 // what `duckdb_bind_get_named_parameter` returns for an absent parameter.
504 let value = unsafe { Value::from_raw(std::ptr::null_mut()) };
505 assert!(value.is_null());
506 assert!(value.as_str().is_err());
507 #[cfg(feature = "duckdb-1-5")]
508 assert!(value.display_string().is_none());
509 assert!(value.struct_child(0).is_none());
510 }
511}