quack-rs 0.12.0

Production-grade Rust SDK for building DuckDB loadable extensions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
// SPDX-License-Identifier: MIT
// Copyright 2026 Tom F. <https://github.com/tomtom215/>
// My way of giving something small back to the open source community
// and encouraging more Rust development!

//! RAII wrapper around `DuckDB` values (`duckdb_value`).
//!
//! [`Value`] provides safe, typed access to `DuckDB` values returned from bind
//! parameter extraction, configuration options, and other APIs. It automatically
//! calls [`duckdb_destroy_value`] on drop, eliminating the manual cleanup that
//! every extension author currently has to remember.
//!
//! # Example
//!
//! ```rust,no_run
//! use quack_rs::value::Value;
//! use quack_rs::table::BindInfo;
//! use libduckdb_sys::duckdb_bind_info;
//!
//! unsafe extern "C" fn my_bind(info: duckdb_bind_info) {
//!     let bind = unsafe { BindInfo::new(info) };
//!     // RAII: Value is destroyed automatically when it goes out of scope.
//!     let val = unsafe { Value::from_raw(bind.get_parameter(0)) };
//!     if let Ok(s) = val.as_str() {
//!         // use s...
//!     }
//! }
//! ```

use std::ffi::CStr;
use std::os::raw::c_char;

use libduckdb_sys::{
    duckdb_destroy_value, duckdb_free, duckdb_get_bool, duckdb_get_double, duckdb_get_float,
    duckdb_get_hugeint, duckdb_get_int16, duckdb_get_int32, duckdb_get_int64, duckdb_get_int8,
    duckdb_get_uint16, duckdb_get_uint32, duckdb_get_uint64, duckdb_get_uint8, duckdb_get_varchar,
    duckdb_value,
};

use crate::error::ExtensionError;

/// An owned, RAII-managed `DuckDB` value.
///
/// When dropped, the underlying `duckdb_value` handle is destroyed via
/// [`duckdb_destroy_value`]. This eliminates the manual `duckdb_destroy_value`
/// calls that are easy to forget and lead to memory leaks.
///
/// # Creation
///
/// Obtain a `Value` from:
/// - [`BindInfo::get_parameter_value`][crate::table::BindInfo::get_parameter_value]
/// - [`BindInfo::get_named_parameter_value`][crate::table::BindInfo::get_named_parameter_value]
/// - [`Value::from_raw`] (escape hatch for raw `duckdb_value` handles)
///
/// # Extraction
///
/// Use typed accessors to extract the underlying data:
/// - [`as_str`][Value::as_str] — VARCHAR → `String`
/// - [`as_i32`][Value::as_i32] — INTEGER → `i32`
/// - [`as_i64`][Value::as_i64] — BIGINT → `i64`
/// - [`as_f32`][Value::as_f32] — FLOAT → `f32`
/// - [`as_f64`][Value::as_f64] — DOUBLE → `f64`
/// - [`as_bool`][Value::as_bool] — BOOLEAN → `bool`
pub struct Value {
    raw: duckdb_value,
}

impl Value {
    /// Wraps a raw `duckdb_value` handle.
    ///
    /// The returned `Value` takes ownership and will call `duckdb_destroy_value`
    /// on drop.
    ///
    /// # Safety
    ///
    /// `raw` must be a valid `duckdb_value` obtained from a `DuckDB` API call
    /// (e.g., `duckdb_bind_get_parameter`). The caller must not destroy the
    /// value after passing it to this function.
    #[inline]
    #[must_use]
    pub const unsafe fn from_raw(raw: duckdb_value) -> Self {
        Self { raw }
    }

    /// Extracts the value as a `String` (VARCHAR).
    ///
    /// Internally calls `duckdb_get_varchar` and frees the returned C string
    /// with `duckdb_free`. Returns an error if the string is not valid UTF-8
    /// or if the value handle is null.
    ///
    /// # Errors
    ///
    /// Returns `ExtensionError` if the value is null or contains invalid UTF-8.
    pub fn as_str(&self) -> Result<String, ExtensionError> {
        if self.raw.is_null() {
            return Err(ExtensionError::new("Value is null"));
        }
        // SAFETY: self.raw is a valid duckdb_value per constructor contract.
        let c_str: *mut c_char = unsafe { duckdb_get_varchar(self.raw) };
        if c_str.is_null() {
            return Err(ExtensionError::new("duckdb_get_varchar returned null"));
        }
        // SAFETY: c_str is a valid null-terminated C string allocated by DuckDB.
        let result = unsafe { CStr::from_ptr(c_str) }
            .to_str()
            .map(str::to_owned)
            .map_err(|_| ExtensionError::new("Value contains invalid UTF-8"));
        // SAFETY: c_str was allocated by DuckDB and must be freed with duckdb_free.
        unsafe { duckdb_free(c_str.cast()) };
        result
    }

    /// Extracts the value as an `i32` (INTEGER).
    ///
    /// `DuckDB` will attempt to cast the value to INTEGER. If the value is not
    /// numeric, this returns 0.
    #[inline]
    #[must_use]
    pub fn as_i32(&self) -> i32 {
        // SAFETY: self.raw is valid per constructor contract.
        unsafe { duckdb_get_int32(self.raw) }
    }

    /// Extracts the value as an `i64` (BIGINT).
    ///
    /// `DuckDB` will attempt to cast the value to BIGINT. If the value is not
    /// numeric, this returns 0.
    #[inline]
    #[must_use]
    pub fn as_i64(&self) -> i64 {
        // SAFETY: self.raw is valid per constructor contract.
        unsafe { duckdb_get_int64(self.raw) }
    }

    /// Extracts the value as an `f32` (FLOAT).
    ///
    /// `DuckDB` will attempt to cast the value to FLOAT. If the value is not
    /// numeric, this returns 0.0.
    #[inline]
    #[must_use]
    pub fn as_f32(&self) -> f32 {
        // SAFETY: self.raw is valid per constructor contract.
        unsafe { duckdb_get_float(self.raw) }
    }

    /// Extracts the value as an `f64` (DOUBLE).
    ///
    /// `DuckDB` will attempt to cast the value to DOUBLE. If the value is not
    /// numeric, this returns 0.0.
    #[inline]
    #[must_use]
    pub fn as_f64(&self) -> f64 {
        // SAFETY: self.raw is valid per constructor contract.
        unsafe { duckdb_get_double(self.raw) }
    }

    /// Extracts the value as a `bool` (BOOLEAN).
    ///
    /// `DuckDB` will attempt to cast the value to BOOLEAN. If the value is not
    /// convertible, this returns `false`.
    #[inline]
    #[must_use]
    pub fn as_bool(&self) -> bool {
        // SAFETY: self.raw is valid per constructor contract.
        unsafe { duckdb_get_bool(self.raw) }
    }

    /// Extracts the value as an `i8` (TINYINT).
    ///
    /// `DuckDB` will attempt to cast the value to TINYINT. If the value is not
    /// numeric, this returns 0.
    #[inline]
    #[must_use]
    pub fn as_i8(&self) -> i8 {
        // SAFETY: self.raw is valid per constructor contract.
        unsafe { duckdb_get_int8(self.raw) }
    }

    /// Extracts the value as an `i16` (SMALLINT).
    ///
    /// `DuckDB` will attempt to cast the value to SMALLINT. If the value is not
    /// numeric, this returns 0.
    #[inline]
    #[must_use]
    pub fn as_i16(&self) -> i16 {
        // SAFETY: self.raw is valid per constructor contract.
        unsafe { duckdb_get_int16(self.raw) }
    }

    /// Extracts the value as a `u8` (UTINYINT).
    ///
    /// `DuckDB` will attempt to cast the value to UTINYINT. If the value is not
    /// numeric, this returns 0.
    #[inline]
    #[must_use]
    pub fn as_u8(&self) -> u8 {
        // SAFETY: self.raw is valid per constructor contract.
        unsafe { duckdb_get_uint8(self.raw) }
    }

    /// Extracts the value as a `u16` (USMALLINT).
    ///
    /// `DuckDB` will attempt to cast the value to USMALLINT. If the value is not
    /// numeric, this returns 0.
    #[inline]
    #[must_use]
    pub fn as_u16(&self) -> u16 {
        // SAFETY: self.raw is valid per constructor contract.
        unsafe { duckdb_get_uint16(self.raw) }
    }

    /// Extracts the value as a `u32` (UINTEGER).
    ///
    /// `DuckDB` will attempt to cast the value to UINTEGER. If the value is not
    /// numeric, this returns 0.
    #[inline]
    #[must_use]
    pub fn as_u32(&self) -> u32 {
        // SAFETY: self.raw is valid per constructor contract.
        unsafe { duckdb_get_uint32(self.raw) }
    }

    /// Extracts the value as a `u64` (UBIGINT).
    ///
    /// `DuckDB` will attempt to cast the value to UBIGINT. If the value is not
    /// numeric, this returns 0.
    #[inline]
    #[must_use]
    pub fn as_u64(&self) -> u64 {
        // SAFETY: self.raw is valid per constructor contract.
        unsafe { duckdb_get_uint64(self.raw) }
    }

    /// Extracts the value as an `i128` (HUGEINT).
    ///
    /// `DuckDB` returns HUGEINT as `{ lower: u64, upper: i64 }`. This method
    /// reconstructs the full `i128` value.
    #[inline]
    #[must_use]
    pub fn as_i128(&self) -> i128 {
        // SAFETY: self.raw is valid per constructor contract.
        let h = unsafe { duckdb_get_hugeint(self.raw) };
        #[allow(clippy::cast_lossless)]
        let result = (h.upper as i128) << 64 | (h.lower as i128);
        result
    }

    /// Extracts the value as a `String`, returning `default` on failure.
    ///
    /// Convenience for `val.as_str().unwrap_or_else(|_| default.to_owned())`.
    #[inline]
    #[must_use]
    pub fn as_str_or(&self, default: &str) -> String {
        self.as_str().unwrap_or_else(|_| default.to_owned())
    }

    /// Extracts the value as a `String`, returning an empty string on failure.
    ///
    /// Convenience for `val.as_str().unwrap_or_default()`.
    #[inline]
    #[must_use]
    pub fn as_str_or_default(&self) -> String {
        self.as_str().unwrap_or_default()
    }

    /// Extracts the value as an `i32`, returning `default` if the handle is null.
    #[inline]
    #[must_use]
    pub fn as_i32_or(&self, default: i32) -> i32 {
        if self.is_null() {
            default
        } else {
            self.as_i32()
        }
    }

    /// Extracts the value as an `i64`, returning `default` if the handle is null.
    #[inline]
    #[must_use]
    pub fn as_i64_or(&self, default: i64) -> i64 {
        if self.is_null() {
            default
        } else {
            self.as_i64()
        }
    }

    /// Extracts the value as an `f32`, returning `default` if the handle is null.
    #[inline]
    #[must_use]
    pub fn as_f32_or(&self, default: f32) -> f32 {
        if self.is_null() {
            default
        } else {
            self.as_f32()
        }
    }

    /// Extracts the value as an `f64`, returning `default` if the handle is null.
    #[inline]
    #[must_use]
    pub fn as_f64_or(&self, default: f64) -> f64 {
        if self.is_null() {
            default
        } else {
            self.as_f64()
        }
    }

    /// Extracts the value as a `bool`, returning `default` if the handle is null.
    #[inline]
    #[must_use]
    pub fn as_bool_or(&self, default: bool) -> bool {
        if self.is_null() {
            default
        } else {
            self.as_bool()
        }
    }

    /// Extracts the value as an `i8`, returning `default` if the handle is null.
    #[inline]
    #[must_use]
    pub fn as_i8_or(&self, default: i8) -> i8 {
        if self.is_null() {
            default
        } else {
            self.as_i8()
        }
    }

    /// Extracts the value as an `i16`, returning `default` if the handle is null.
    #[inline]
    #[must_use]
    pub fn as_i16_or(&self, default: i16) -> i16 {
        if self.is_null() {
            default
        } else {
            self.as_i16()
        }
    }

    /// Extracts the value as a `u8`, returning `default` if the handle is null.
    #[inline]
    #[must_use]
    pub fn as_u8_or(&self, default: u8) -> u8 {
        if self.is_null() {
            default
        } else {
            self.as_u8()
        }
    }

    /// Extracts the value as a `u16`, returning `default` if the handle is null.
    #[inline]
    #[must_use]
    pub fn as_u16_or(&self, default: u16) -> u16 {
        if self.is_null() {
            default
        } else {
            self.as_u16()
        }
    }

    /// Extracts the value as a `u32`, returning `default` if the handle is null.
    #[inline]
    #[must_use]
    pub fn as_u32_or(&self, default: u32) -> u32 {
        if self.is_null() {
            default
        } else {
            self.as_u32()
        }
    }

    /// Extracts the value as a `u64`, returning `default` if the handle is null.
    #[inline]
    #[must_use]
    pub fn as_u64_or(&self, default: u64) -> u64 {
        if self.is_null() {
            default
        } else {
            self.as_u64()
        }
    }

    /// Extracts the value as an `i128`, returning `default` if the handle is null.
    #[inline]
    #[must_use]
    pub fn as_i128_or(&self, default: i128) -> i128 {
        if self.is_null() {
            default
        } else {
            self.as_i128()
        }
    }

    /// Returns `true` if the underlying handle is null.
    #[inline]
    #[must_use]
    pub const fn is_null(&self) -> bool {
        self.raw.is_null()
    }

    /// Returns the raw `duckdb_value` handle without consuming the `Value`.
    ///
    /// The `Value` still owns the handle and will destroy it on drop.
    #[inline]
    #[must_use]
    pub const fn as_raw(&self) -> duckdb_value {
        self.raw
    }

    /// Consumes the `Value` and returns the raw `duckdb_value` handle.
    ///
    /// The caller takes ownership and is responsible for calling
    /// `duckdb_destroy_value` when done.
    #[inline]
    #[must_use]
    pub const fn into_raw(self) -> duckdb_value {
        let raw = self.raw;
        std::mem::forget(self);
        raw
    }
}

impl Drop for Value {
    fn drop(&mut self) {
        if !self.raw.is_null() {
            // SAFETY: self.raw is a valid duckdb_value that we own.
            unsafe { duckdb_destroy_value(&raw mut self.raw) };
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn null_value_is_null() {
        let val = unsafe { Value::from_raw(std::ptr::null_mut()) };
        assert!(val.is_null());
    }

    #[test]
    fn null_value_as_str_returns_error() {
        let val = unsafe { Value::from_raw(std::ptr::null_mut()) };
        assert!(val.as_str().is_err());
    }

    #[test]
    fn into_raw_prevents_double_free() {
        let val = unsafe { Value::from_raw(std::ptr::null_mut()) };
        let raw = val.into_raw();
        assert!(raw.is_null());
        // No double-free: Value was forgotten via into_raw.
    }

    #[test]
    fn size_of_value() {
        assert_eq!(std::mem::size_of::<Value>(), std::mem::size_of::<usize>());
    }

    #[test]
    fn as_str_or_returns_default_for_null() {
        let val = unsafe { Value::from_raw(std::ptr::null_mut()) };
        assert_eq!(val.as_str_or("fallback"), "fallback");
    }

    #[test]
    fn as_str_or_default_returns_empty_for_null() {
        let val = unsafe { Value::from_raw(std::ptr::null_mut()) };
        assert_eq!(val.as_str_or_default(), "");
    }

    #[test]
    fn as_i64_or_returns_default_for_null() {
        let val = unsafe { Value::from_raw(std::ptr::null_mut()) };
        assert_eq!(val.as_i64_or(99), 99);
    }

    #[test]
    fn as_i32_or_returns_default_for_null() {
        let val = unsafe { Value::from_raw(std::ptr::null_mut()) };
        assert_eq!(val.as_i32_or(42), 42);
    }

    #[test]
    fn as_bool_or_returns_default_for_null() {
        let val = unsafe { Value::from_raw(std::ptr::null_mut()) };
        assert!(val.as_bool_or(true));
        assert!(!val.as_bool_or(false));
    }

    #[test]
    fn as_f64_or_returns_default_for_null() {
        let val = unsafe { Value::from_raw(std::ptr::null_mut()) };
        assert!((val.as_f64_or(2.72) - 2.72).abs() < f64::EPSILON);
    }

    #[test]
    fn as_f32_or_returns_default_for_null() {
        let val = unsafe { Value::from_raw(std::ptr::null_mut()) };
        assert!((val.as_f32_or(2.5) - 2.5).abs() < f32::EPSILON);
    }
}