Skip to main content

quack_rs/vector/
struct_reader.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//! Batched, typed reader for STRUCT input vectors.
7//!
8//! [`StructReader`] pre-creates [`VectorReader`]s for every field at construction,
9//! then exposes typed `read_*` methods that take `(row, field_idx)`.
10//! This is the read-side counterpart to [`StructWriter`][super::StructWriter].
11//!
12//! # Example
13//!
14//! ```rust,no_run
15//! use quack_rs::vector::StructReader;
16//! use libduckdb_sys::duckdb_vector;
17//!
18//! // Inside a scan callback, given a STRUCT input vector with 3 fields:
19//! // let sr = unsafe { StructReader::new(struct_vec, 3, row_count) };
20//! // for row in 0..row_count {
21//! //     let name = unsafe { sr.read_str(row, 0) };
22//! //     let age = unsafe { sr.read_i32(row, 1) };
23//! //     let active = unsafe { sr.read_bool(row, 2) };
24//! // }
25//! ```
26
27use libduckdb_sys::duckdb_vector;
28
29use crate::interval::DuckInterval;
30use crate::vector::complex::StructVector;
31use crate::vector::VectorReader;
32
33/// A batched reader for STRUCT input vectors.
34///
35/// Pre-creates a [`VectorReader`] for every field at construction, allowing
36/// direct typed reads without repeated `duckdb_struct_vector_get_child` calls.
37#[derive(Debug)]
38pub struct StructReader {
39    vector: duckdb_vector,
40    fields: Vec<VectorReader>,
41}
42
43impl StructReader {
44    /// Creates a new `StructReader` for a STRUCT vector with `field_count` fields.
45    ///
46    /// # Safety
47    ///
48    /// - `vector` must be a valid `DuckDB` STRUCT vector.
49    /// - `field_count` must match the number of fields in the STRUCT type.
50    /// - `row_count` must match the number of rows in the parent chunk.
51    /// - The vector must remain valid for the lifetime of this reader.
52    pub unsafe fn new(vector: duckdb_vector, field_count: usize, row_count: usize) -> Self {
53        let mut fields = Vec::with_capacity(field_count);
54        for idx in 0..field_count {
55            // SAFETY: caller guarantees vector is valid STRUCT with field_count fields.
56            fields.push(unsafe { StructVector::field_reader(vector, idx, row_count) });
57        }
58        Self { vector, fields }
59    }
60
61    /// Returns the number of fields in this struct reader.
62    #[cfg_attr(test, mutants::skip)]
63    #[must_use]
64    #[inline]
65    pub fn field_count(&self) -> usize {
66        self.fields.len()
67    }
68
69    /// Returns a reference to the [`VectorReader`] for the given field.
70    ///
71    /// # Panics
72    ///
73    /// Panics if `field_idx >= field_count`.
74    #[must_use]
75    #[inline]
76    pub fn field(&self, field_idx: usize) -> &VectorReader {
77        &self.fields[field_idx]
78    }
79
80    /// Returns the raw `duckdb_vector` handle for the given field.
81    ///
82    /// Use this when a struct field has a complex type (LIST, MAP, ARRAY) that
83    /// requires operations beyond simple scalar reads — for example, calling
84    /// [`ListVector::get_entry`][crate::vector::complex::ListVector::get_entry] or
85    /// [`ListVector::child_reader`][crate::vector::complex::ListVector::child_reader].
86    ///
87    /// # Safety
88    ///
89    /// - `field_idx` must be a valid field index (0 ≤ `field_idx` < `field_count`).
90    /// - The returned vector is borrowed from the parent STRUCT vector and must
91    ///   not outlive it.
92    #[must_use]
93    #[inline]
94    pub unsafe fn child_vector(&self, field_idx: usize) -> duckdb_vector {
95        // SAFETY: `StructVector::get_child` needs a live STRUCT vector and a field
96        // index below its field count. `new`'s contract makes `self.vector` a valid
97        // STRUCT vector with `field_count` fields for this reader's lifetime, and
98        // this function's `# Safety` clause requires `field_idx < field_count`.
99        unsafe { StructVector::get_child(self.vector, field_idx) }
100    }
101
102    /// Returns `true` if the value at `row` in field `field_idx` is not NULL.
103    ///
104    /// # Safety
105    ///
106    /// `row` must be less than the row count.
107    ///
108    /// # Panics
109    ///
110    /// Panics if `field_idx >= field_count`.
111    #[inline]
112    pub unsafe fn is_valid(&self, row: usize, field_idx: usize) -> bool {
113        // SAFETY: `VectorReader::is_valid` needs `row` below the reader's row count.
114        // `self.fields[field_idx]` (bounds-checked) was built by `new` over STRUCT
115        // child `field_idx` with the parent's `row_count`, and this function's
116        // `# Safety` clause requires `row` below that count.
117        unsafe { self.fields[field_idx].is_valid(row) }
118    }
119
120    /// Reads a `bool` (BOOLEAN) value from field `field_idx` at row `row`.
121    ///
122    /// # Safety
123    ///
124    /// - `row` must be less than the row count.
125    /// - The field at `field_idx` must have `BOOLEAN` type.
126    ///
127    /// # Panics
128    ///
129    /// Panics if `field_idx >= field_count`.
130    #[inline]
131    pub unsafe fn read_bool(&self, row: usize, field_idx: usize) -> bool {
132        // SAFETY: `VectorReader::read_bool` needs `row` below its row count and a
133        // BOOLEAN column. `self.fields[field_idx]` (bounds-checked) was built by `new`
134        // over STRUCT child `field_idx` with the parent's `row_count`, and the
135        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
136        // `row` below that count and a BOOLEAN field.
137        unsafe { self.fields[field_idx].read_bool(row) }
138    }
139
140    /// Reads a VARCHAR value from field `field_idx` at row `row`.
141    ///
142    /// # Safety
143    ///
144    /// - `row` must be less than the row count.
145    /// - The field at `field_idx` must have `VARCHAR` type.
146    /// - The field must not be NULL at `row` (check [`is_valid`][Self::is_valid]
147    ///   first): a NULL row may hold a stale pointer; see
148    ///   [`VectorReader::read_str`].
149    ///
150    /// # Panics
151    ///
152    /// Panics if `field_idx >= field_count`.
153    #[inline]
154    pub unsafe fn read_str(&self, row: usize, field_idx: usize) -> &str {
155        // SAFETY: `VectorReader::read_str` needs `row` below its row count and a
156        // VARCHAR column. `self.fields[field_idx]` (bounds-checked) was built by `new`
157        // over STRUCT child `field_idx` with the parent's `row_count`, and the
158        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
159        // `row` below that count and a VARCHAR field.
160        // The result borrows `&self`, and the string heap it may point into belongs
161        // to the child vector, which `new`'s contract keeps valid for the reader's
162        // lifetime.
163        unsafe { self.fields[field_idx].read_str(row) }
164    }
165
166    /// Reads an `i8` (TINYINT) value from field `field_idx` at row `row`.
167    ///
168    /// # Safety
169    ///
170    /// See [`read_bool`][Self::read_bool].
171    #[inline]
172    pub unsafe fn read_i8(&self, row: usize, field_idx: usize) -> i8 {
173        // SAFETY: `VectorReader::read_i8` needs `row` below its row count and a
174        // TINYINT column. `self.fields[field_idx]` (bounds-checked) was built by `new`
175        // over STRUCT child `field_idx` with the parent's `row_count`, and the
176        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
177        // `row` below that count and a TINYINT field.
178        unsafe { self.fields[field_idx].read_i8(row) }
179    }
180
181    /// Reads an `i16` (SMALLINT) value.
182    ///
183    /// # Safety
184    ///
185    /// See [`read_bool`][Self::read_bool].
186    #[inline]
187    pub unsafe fn read_i16(&self, row: usize, field_idx: usize) -> i16 {
188        // SAFETY: `VectorReader::read_i16` needs `row` below its row count and a
189        // SMALLINT column. `self.fields[field_idx]` (bounds-checked) was built by `new`
190        // over STRUCT child `field_idx` with the parent's `row_count`, and the
191        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
192        // `row` below that count and a SMALLINT field.
193        unsafe { self.fields[field_idx].read_i16(row) }
194    }
195
196    /// Reads an `i32` (INTEGER) value.
197    ///
198    /// # Safety
199    ///
200    /// See [`read_bool`][Self::read_bool].
201    #[inline]
202    pub unsafe fn read_i32(&self, row: usize, field_idx: usize) -> i32 {
203        // SAFETY: `VectorReader::read_i32` needs `row` below its row count and a
204        // INTEGER column. `self.fields[field_idx]` (bounds-checked) was built by `new`
205        // over STRUCT child `field_idx` with the parent's `row_count`, and the
206        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
207        // `row` below that count and a INTEGER field.
208        unsafe { self.fields[field_idx].read_i32(row) }
209    }
210
211    /// Reads an `i64` (BIGINT) value.
212    ///
213    /// # Safety
214    ///
215    /// See [`read_bool`][Self::read_bool].
216    #[inline]
217    pub unsafe fn read_i64(&self, row: usize, field_idx: usize) -> i64 {
218        // SAFETY: `VectorReader::read_i64` needs `row` below its row count and a
219        // BIGINT column. `self.fields[field_idx]` (bounds-checked) was built by `new`
220        // over STRUCT child `field_idx` with the parent's `row_count`, and the
221        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
222        // `row` below that count and a BIGINT field.
223        unsafe { self.fields[field_idx].read_i64(row) }
224    }
225
226    /// Reads an `i128` (HUGEINT) value.
227    ///
228    /// # Safety
229    ///
230    /// See [`read_bool`][Self::read_bool].
231    #[inline]
232    pub unsafe fn read_i128(&self, row: usize, field_idx: usize) -> i128 {
233        // SAFETY: `VectorReader::read_i128` needs `row` below its row count and a
234        // HUGEINT column. `self.fields[field_idx]` (bounds-checked) was built by `new`
235        // over STRUCT child `field_idx` with the parent's `row_count`, and the
236        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
237        // `row` below that count and a HUGEINT field.
238        unsafe { self.fields[field_idx].read_i128(row) }
239    }
240
241    /// Reads a `u8` (UTINYINT) value.
242    ///
243    /// # Safety
244    ///
245    /// See [`read_bool`][Self::read_bool].
246    #[inline]
247    pub unsafe fn read_u8(&self, row: usize, field_idx: usize) -> u8 {
248        // SAFETY: `VectorReader::read_u8` needs `row` below its row count and a
249        // UTINYINT column. `self.fields[field_idx]` (bounds-checked) was built by `new`
250        // over STRUCT child `field_idx` with the parent's `row_count`, and the
251        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
252        // `row` below that count and a UTINYINT field.
253        unsafe { self.fields[field_idx].read_u8(row) }
254    }
255
256    /// Reads a `u16` (USMALLINT) value.
257    ///
258    /// # Safety
259    ///
260    /// See [`read_bool`][Self::read_bool].
261    #[inline]
262    pub unsafe fn read_u16(&self, row: usize, field_idx: usize) -> u16 {
263        // SAFETY: `VectorReader::read_u16` needs `row` below its row count and a
264        // USMALLINT column. `self.fields[field_idx]` (bounds-checked) was built by `new`
265        // over STRUCT child `field_idx` with the parent's `row_count`, and the
266        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
267        // `row` below that count and a USMALLINT field.
268        unsafe { self.fields[field_idx].read_u16(row) }
269    }
270
271    /// Reads a `u32` (UINTEGER) value.
272    ///
273    /// # Safety
274    ///
275    /// See [`read_bool`][Self::read_bool].
276    #[inline]
277    pub unsafe fn read_u32(&self, row: usize, field_idx: usize) -> u32 {
278        // SAFETY: `VectorReader::read_u32` needs `row` below its row count and a
279        // UINTEGER column. `self.fields[field_idx]` (bounds-checked) was built by `new`
280        // over STRUCT child `field_idx` with the parent's `row_count`, and the
281        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
282        // `row` below that count and a UINTEGER field.
283        unsafe { self.fields[field_idx].read_u32(row) }
284    }
285
286    /// Reads a `u64` (UBIGINT) value.
287    ///
288    /// # Safety
289    ///
290    /// See [`read_bool`][Self::read_bool].
291    #[inline]
292    pub unsafe fn read_u64(&self, row: usize, field_idx: usize) -> u64 {
293        // SAFETY: `VectorReader::read_u64` needs `row` below its row count and a
294        // UBIGINT column. `self.fields[field_idx]` (bounds-checked) was built by `new`
295        // over STRUCT child `field_idx` with the parent's `row_count`, and the
296        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
297        // `row` below that count and a UBIGINT field.
298        unsafe { self.fields[field_idx].read_u64(row) }
299    }
300
301    /// Reads an `f32` (FLOAT) value.
302    ///
303    /// # Safety
304    ///
305    /// See [`read_bool`][Self::read_bool].
306    #[inline]
307    pub unsafe fn read_f32(&self, row: usize, field_idx: usize) -> f32 {
308        // SAFETY: `VectorReader::read_f32` needs `row` below its row count and a
309        // FLOAT column. `self.fields[field_idx]` (bounds-checked) was built by `new`
310        // over STRUCT child `field_idx` with the parent's `row_count`, and the
311        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
312        // `row` below that count and a FLOAT field.
313        unsafe { self.fields[field_idx].read_f32(row) }
314    }
315
316    /// Reads an `f64` (DOUBLE) value.
317    ///
318    /// # Safety
319    ///
320    /// See [`read_bool`][Self::read_bool].
321    #[inline]
322    pub unsafe fn read_f64(&self, row: usize, field_idx: usize) -> f64 {
323        // SAFETY: `VectorReader::read_f64` needs `row` below its row count and a
324        // DOUBLE column. `self.fields[field_idx]` (bounds-checked) was built by `new`
325        // over STRUCT child `field_idx` with the parent's `row_count`, and the
326        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
327        // `row` below that count and a DOUBLE field.
328        unsafe { self.fields[field_idx].read_f64(row) }
329    }
330
331    /// Reads an INTERVAL value.
332    ///
333    /// # Safety
334    ///
335    /// See [`read_bool`][Self::read_bool].
336    #[inline]
337    pub unsafe fn read_interval(&self, row: usize, field_idx: usize) -> DuckInterval {
338        // SAFETY: `VectorReader::read_interval` needs `row` below its row count and a
339        // INTERVAL column. `self.fields[field_idx]` (bounds-checked) was built by `new`
340        // over STRUCT child `field_idx` with the parent's `row_count`, and the
341        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
342        // `row` below that count and a INTERVAL field.
343        unsafe { self.fields[field_idx].read_interval(row) }
344    }
345
346    /// Reads a DATE value (days since epoch).
347    ///
348    /// # Safety
349    ///
350    /// See [`read_bool`][Self::read_bool].
351    #[inline]
352    pub unsafe fn read_date(&self, row: usize, field_idx: usize) -> i32 {
353        // SAFETY: `VectorReader::read_date` needs `row` below its row count and a
354        // DATE column. `self.fields[field_idx]` (bounds-checked) was built by `new`
355        // over STRUCT child `field_idx` with the parent's `row_count`, and the
356        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
357        // `row` below that count and a DATE field.
358        unsafe { self.fields[field_idx].read_date(row) }
359    }
360
361    /// Reads a TIMESTAMP value (microseconds since epoch).
362    ///
363    /// # Safety
364    ///
365    /// See [`read_bool`][Self::read_bool].
366    #[inline]
367    pub unsafe fn read_timestamp(&self, row: usize, field_idx: usize) -> i64 {
368        // SAFETY: `VectorReader::read_timestamp` needs `row` below its row count and a
369        // TIMESTAMP column. `self.fields[field_idx]` (bounds-checked) was built by `new`
370        // over STRUCT child `field_idx` with the parent's `row_count`, and the
371        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
372        // `row` below that count and a TIMESTAMP field.
373        unsafe { self.fields[field_idx].read_timestamp(row) }
374    }
375
376    /// Reads a TIME value (microseconds since midnight).
377    ///
378    /// # Safety
379    ///
380    /// See [`read_bool`][Self::read_bool].
381    #[inline]
382    pub unsafe fn read_time(&self, row: usize, field_idx: usize) -> i64 {
383        // SAFETY: `VectorReader::read_time` needs `row` below its row count and a
384        // TIME column. `self.fields[field_idx]` (bounds-checked) was built by `new`
385        // over STRUCT child `field_idx` with the parent's `row_count`, and the
386        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
387        // `row` below that count and a TIME field.
388        unsafe { self.fields[field_idx].read_time(row) }
389    }
390
391    /// Reads a `BLOB` (binary) value from field `field_idx` at row `row`.
392    ///
393    /// # Safety
394    ///
395    /// As for [`read_bool`][Self::read_bool], and the field must not be NULL at
396    /// `row` (check [`is_valid`][Self::is_valid] first): a NULL row may hold a
397    /// stale pointer; see [`VectorReader::read_blob`].
398    #[inline]
399    pub unsafe fn read_blob(&self, row: usize, field_idx: usize) -> &[u8] {
400        // SAFETY: `VectorReader::read_blob` needs `row` below its row count and a
401        // BLOB column. `self.fields[field_idx]` (bounds-checked) was built by `new`
402        // over STRUCT child `field_idx` with the parent's `row_count`, and the
403        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
404        // `row` below that count and a BLOB field.
405        // The result borrows `&self`, and the string heap it may point into belongs
406        // to the child vector, which `new`'s contract keeps valid for the reader's
407        // lifetime.
408        unsafe { self.fields[field_idx].read_blob(row) }
409    }
410
411    /// Reads a `UUID`'s textual 128 bits from field `field_idx` at row `row`.
412    ///
413    /// See [`VectorReader::read_uuid`][crate::vector::VectorReader::read_uuid]
414    /// for why this is not the raw `HUGEINT` storage.
415    ///
416    /// # Safety
417    ///
418    /// See [`read_bool`][Self::read_bool].
419    #[inline]
420    pub unsafe fn read_uuid(&self, row: usize, field_idx: usize) -> u128 {
421        // SAFETY: `VectorReader::read_uuid` needs `row` below its row count and a
422        // UUID column. `self.fields[field_idx]` (bounds-checked) was built by `new`
423        // over STRUCT child `field_idx` with the parent's `row_count`, and the
424        // `# Safety` contract (`read_bool`'s, for the field's own type) gives
425        // `row` below that count and a UUID field.
426        unsafe { self.fields[field_idx].read_uuid(row) }
427    }
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    #[test]
435    fn struct_reader_field_count() {
436        let sr = StructReader {
437            vector: std::ptr::null_mut(),
438            fields: Vec::new(),
439        };
440        assert_eq!(sr.field_count(), 0);
441    }
442
443    #[test]
444    fn size_of_struct_reader() {
445        assert_eq!(
446            std::mem::size_of::<StructReader>(),
447            4 * std::mem::size_of::<usize>() // vector ptr + Vec (ptr + len + cap)
448        );
449    }
450}