Skip to main content

quack_rs/value/
blob.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
6use libduckdb_sys::{duckdb_blob, duckdb_free, duckdb_get_blob};
7
8use super::Value;
9use crate::error::ExtensionError;
10use crate::types::TypeId;
11
12fn blob_size(blob: &duckdb_blob) -> Result<Option<usize>, ExtensionError> {
13    if blob.data.is_null() {
14        return if blob.size == 0 {
15            Ok(None)
16        } else {
17            Err(ExtensionError::new("duckdb_get_blob returned null data"))
18        };
19    }
20    usize::try_from(blob.size)
21        .map(Some)
22        .map_err(|_| ExtensionError::new("duckdb_get_blob returned an unsupported blob size"))
23}
24
25/// Refuses every type but `BLOB`: `duckdb_get_blob` casts anything else with a
26/// throwing cast. `id` is the value's type, `None` if `DuckDB` reported one
27/// this build does not name.
28fn require_blob(id: Option<TypeId>) -> Result<(), ExtensionError> {
29    if id == Some(TypeId::Blob) {
30        Ok(())
31    } else {
32        Err(ExtensionError::new(format!(
33            "as_blob: value is {id:?}, not BLOB"
34        )))
35    }
36}
37
38/// Frees the data of a blob `duckdb_get_blob` returned.
39///
40/// # Safety
41///
42/// `data` must be null or a `duckdb_blob::data` pointer from
43/// `duckdb_get_blob` that has not been freed.
44#[cfg_attr(test, mutants::skip)] // DuckDB allocator effects are not observable from safe Rust tests.
45unsafe fn free_blob_data(data: *mut core::ffi::c_void) {
46    if !data.is_null() {
47        // SAFETY: `data` is non-null (checked just above). This private helper's only
48        // callers, both in `as_blob`, pass the `blob.data` that `duckdb_get_blob` just
49        // `malloc`ed (duckdb_value-c.cpp) and free it exactly once, on mutually exclusive
50        // paths; duckdb.h says to release it with `duckdb_free`, which is `free`
51        // (helper-c.cpp).
52        unsafe { duckdb_free(data) };
53    }
54}
55
56impl Value {
57    /// Extracts the value as an owned `Vec<u8>` (`BLOB`).
58    ///
59    /// `DuckDB` allocates the blob's backing buffer; this method copies it into
60    /// an owned `Vec<u8>` and frees the original with `duckdb_free`. The bytes
61    /// are copied without UTF-8 validation.
62    ///
63    /// # Errors
64    ///
65    /// Returns `ExtensionError` if the value handle is null, the value is SQL
66    /// `NULL`, its type is not `BLOB`, `duckdb_get_blob` returns a null data
67    /// pointer for a non-empty blob, or the blob size cannot be represented by
68    /// `usize` on the current platform.
69    ///
70    /// Only a `BLOB` is accepted. `duckdb_get_blob` casts anything else to
71    /// `BLOB` with a *throwing* cast — an `INTEGER`, or a `VARCHAR` with an
72    /// invalid `\x` escape, aborted the process — and it throws on SQL `NULL`
73    /// too. Read a `VARCHAR` with [`as_str`][Self::as_str].
74    pub fn as_blob(&self) -> Result<Vec<u8>, ExtensionError> {
75        if self.raw.is_null() {
76            return Err(ExtensionError::new("Value is null"));
77        }
78        if self.is_sql_null() {
79            return Err(ExtensionError::new("Value is SQL NULL"));
80        }
81        require_blob(self.type_id())?;
82        // SAFETY: self.raw is a live, non-NULL BLOB, so duckdb_get_blob's
83        // cast is the identity and StringValue::Get cannot throw.
84        let blob: duckdb_blob = unsafe { duckdb_get_blob(self.raw) };
85        let size = match blob_size(&blob) {
86            Ok(None) => return Ok(Vec::new()),
87            Ok(Some(size)) => size,
88            Err(error) => {
89                // SAFETY: non-null blob data was allocated by DuckDB. The
90                // helper also accepts null for the invalid-pointer error path.
91                unsafe { free_blob_data(blob.data) };
92                return Err(error);
93            }
94        };
95        // SAFETY: blob.data is a DuckDB-allocated buffer of exactly `blob.size`
96        // bytes, valid until we free it below.
97        let slice = unsafe { std::slice::from_raw_parts(blob.data.cast::<u8>(), size) };
98        let out = slice.to_vec();
99        // SAFETY: blob.data was allocated by DuckDB and must be freed with duckdb_free.
100        unsafe { free_blob_data(blob.data) };
101        Ok(out)
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    #[test]
110    fn blob_size_null_empty_blob_is_valid() {
111        let blob = duckdb_blob {
112            data: std::ptr::null_mut(),
113            size: 0,
114        };
115        assert!(matches!(blob_size(&blob), Ok(None)));
116    }
117
118    #[test]
119    fn blob_size_null_non_empty_blob_is_invalid() {
120        let blob = duckdb_blob {
121            data: std::ptr::null_mut(),
122            size: 1,
123        };
124        assert!(blob_size(&blob).is_err());
125    }
126
127    #[test]
128    fn only_a_blob_type_is_accepted() {
129        assert!(require_blob(Some(TypeId::Blob)).is_ok());
130        let err = require_blob(Some(TypeId::Varchar)).expect_err("VARCHAR is not BLOB");
131        assert_eq!(err.as_str(), "as_blob: value is Some(Varchar), not BLOB");
132        assert!(require_blob(Some(TypeId::Integer)).is_err());
133        let err = require_blob(None).expect_err("an unnamed type is not BLOB");
134        assert_eq!(err.as_str(), "as_blob: value is None, not BLOB");
135    }
136
137    #[test]
138    fn null_value_as_blob_returns_error() {
139        let value = unsafe { Value::from_raw(std::ptr::null_mut()) };
140        assert!(value.as_blob().is_err());
141    }
142
143    #[cfg(feature = "_duckdb-testing")]
144    #[test]
145    fn blob_value_non_utf8_bytes_round_trip() {
146        let _db = crate::testing::InMemoryDb::open().expect("should initialize DuckDB");
147        let payload = [
148            0x80u8, 0xF0, 0x01, 0x42, 0xFF, 0x00, 0xFE, 0x7F, 0xAA, 0x55, 0xC0, 0xAF, 0x90,
149        ];
150        let len = u64::try_from(payload.len()).expect("test payload length fits in u64");
151        // SAFETY: payload points to `len` readable bytes for the duration of the call.
152        let raw = unsafe { libduckdb_sys::duckdb_create_blob(payload.as_ptr(), len) };
153        // SAFETY: duckdb_create_blob returns an owned value handle.
154        let value = unsafe { Value::from_raw(raw) };
155
156        assert_eq!(value.as_blob().expect("blob should be readable"), payload);
157    }
158
159    #[cfg(feature = "_duckdb-testing")]
160    #[test]
161    fn blob_value_empty_bytes_round_trip() {
162        let _db = crate::testing::InMemoryDb::open().expect("should initialize DuckDB");
163        let payload = [];
164        // SAFETY: payload is readable for zero bytes for the duration of the call.
165        let raw = unsafe { libduckdb_sys::duckdb_create_blob(payload.as_ptr(), 0) };
166        // SAFETY: duckdb_create_blob returns an owned value handle.
167        let value = unsafe { Value::from_raw(raw) };
168
169        assert_eq!(
170            value.as_blob().expect("blob should be readable"),
171            Vec::<u8>::new()
172        );
173    }
174}