quack_rs/value/nested.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//! Reading nested values: `LIST` elements, `STRUCT` fields, `MAP` entries.
7
8use libduckdb_sys::duckdb_free;
9
10use super::Value;
11
12impl Value {
13 // ── LIST / STRUCT / MAP extraction ───────────────────────────────────
14
15 /// Number of elements in a `LIST` value.
16 ///
17 /// Returns 0 for non-`LIST` values, an `ARRAY` included: the C API reads
18 /// a `LIST` only. Read an `ARRAY` with
19 /// [`array_items`][Self::array_items].
20 #[inline]
21 #[must_use]
22 pub fn list_len(&self) -> usize {
23 // SAFETY: self.raw is valid per constructor contract.
24 usize::try_from(unsafe { libduckdb_sys::duckdb_get_list_size(self.raw) }).unwrap_or(0)
25 }
26
27 /// Element `index` of a `LIST` value, or `None` if out of range.
28 ///
29 /// The returned [`Value`] owns its handle.
30 #[must_use]
31 pub fn list_child(&self, index: usize) -> Option<Self> {
32 if index >= self.list_len() {
33 return None;
34 }
35 // SAFETY: `index` was bounds-checked against `list_len`.
36 let raw = unsafe {
37 libduckdb_sys::duckdb_get_list_child(self.raw, index as libduckdb_sys::idx_t)
38 };
39 (!raw.is_null()).then(|| Self { raw })
40 }
41
42 /// Collects a `LIST` value into a `Vec` of owned [`Value`]s.
43 ///
44 /// # Example
45 ///
46 /// ```rust,no_run
47 /// # use quack_rs::value::Value;
48 /// # fn demo(paths: &Value) {
49 /// let files: Vec<String> = paths
50 /// .list_items()
51 /// .iter()
52 /// .filter_map(|v| v.as_str().ok())
53 /// .collect();
54 /// # }
55 /// ```
56 #[must_use]
57 pub fn list_items(&self) -> Vec<Self> {
58 (0..self.list_len())
59 .filter_map(|i| self.list_child(i))
60 .collect()
61 }
62
63 /// Field names of a `STRUCT` value, in order.
64 ///
65 /// `DuckDB`'s C API exposes a struct value's children by position only —
66 /// the names live on the value's `LogicalType`. Reading them by hand means
67 /// calling `duckdb_get_value_type`, whose result `duckdb.h` says "must not
68 /// be destroyed" because the *value* owns it, which is exactly the kind of
69 /// borrowed handle it is easy to hand to
70 /// [`LogicalType::from_raw`][crate::types::LogicalType::from_raw] and then
71 /// double-free (pitfall P11). This does the walk without exposing it.
72 ///
73 /// Returns an empty vector for a null handle or a value whose type has no
74 /// struct children. A `UNION` type is stored as a struct of its tag and
75 /// its members, so for a `UNION` value it returns `""` for the tag
76 /// followed by the member names. [`struct_child`][Self::struct_child]
77 /// returns `None` for every index of a `UNION` value; read the active
78 /// member's index with `union_tag` (feature `duckdb-1-5`; its name is
79 /// then `struct_field_names()[tag + 1]`) and its value, as text, with
80 /// [`try_cast`][Self::try_cast] to `VARCHAR`.
81 ///
82 /// Pair it with [`struct_child`][Self::struct_child], which is positional:
83 ///
84 /// ```rust,no_run
85 /// # use quack_rs::value::Value;
86 /// # fn demo(options: &Value) -> Option<String> {
87 /// let names = options.struct_field_names();
88 /// let idx = names.iter().position(|n| n == "compression")?;
89 /// options.struct_child(idx)?.as_str().ok()
90 /// # }
91 /// ```
92 #[must_use]
93 pub fn struct_field_names(&self) -> Vec<String> {
94 if self.raw.is_null() {
95 return Vec::new();
96 }
97 // SAFETY: `self.raw` is a valid duckdb_value per the constructor
98 // contract. The returned type is owned by the value — duckdb.h: "The
99 // type itself must not be destroyed" — so it is only read through, never
100 // wrapped in `LogicalType` and never destroyed here.
101 let logical = unsafe { libduckdb_sys::duckdb_get_value_type(self.raw) };
102 if logical.is_null() {
103 return Vec::new();
104 }
105 // SAFETY: `logical` is non-null and lives as long as `self`.
106 let count = unsafe { libduckdb_sys::duckdb_struct_type_child_count(logical) };
107 (0..count)
108 .map(|i| {
109 // SAFETY: `i < count`. DuckDB allocates the name with
110 // `duckdb_malloc`, so it is freed with `duckdb_free`.
111 let ptr = unsafe { libduckdb_sys::duckdb_struct_type_child_name(logical, i) };
112 if ptr.is_null() {
113 return String::new();
114 }
115 // SAFETY: `ptr` is a NUL-terminated string owned by us.
116 let owned = unsafe { std::ffi::CStr::from_ptr(ptr) }
117 .to_str()
118 .unwrap_or_default()
119 .to_owned();
120 // SAFETY: allocated by DuckDB, freed exactly once here.
121 unsafe { duckdb_free(ptr.cast::<std::os::raw::c_void>()) };
122 owned
123 })
124 .collect()
125 }
126
127 /// Field `index` of a `STRUCT` value, or `None` if the handle is null or the
128 /// index is out of range.
129 ///
130 /// Field names come from the value's `LogicalType`, not from the value
131 /// itself; `DuckDB`'s C API exposes children by position.
132 #[must_use]
133 pub fn struct_child(&self, index: usize) -> Option<Self> {
134 if self.raw.is_null() {
135 return None;
136 }
137 // SAFETY: self.raw is valid; DuckDB returns null for an out-of-range index.
138 let raw = unsafe {
139 libduckdb_sys::duckdb_get_struct_child(self.raw, index as libduckdb_sys::idx_t)
140 };
141 (!raw.is_null()).then(|| Self { raw })
142 }
143
144 /// Number of key/value pairs in a `MAP` value.
145 #[inline]
146 #[must_use]
147 pub fn map_len(&self) -> usize {
148 // SAFETY: self.raw is valid per constructor contract.
149 usize::try_from(unsafe { libduckdb_sys::duckdb_get_map_size(self.raw) }).unwrap_or(0)
150 }
151
152 /// Key at `index` of a `MAP` value, or `None` if out of range.
153 #[must_use]
154 pub fn map_key(&self, index: usize) -> Option<Self> {
155 if index >= self.map_len() {
156 return None;
157 }
158 // SAFETY: `index` was bounds-checked against `map_len`.
159 let raw =
160 unsafe { libduckdb_sys::duckdb_get_map_key(self.raw, index as libduckdb_sys::idx_t) };
161 (!raw.is_null()).then(|| Self { raw })
162 }
163
164 /// Value at `index` of a `MAP` value, or `None` if out of range.
165 #[must_use]
166 pub fn map_value(&self, index: usize) -> Option<Self> {
167 if index >= self.map_len() {
168 return None;
169 }
170 // SAFETY: `index` was bounds-checked against `map_len`.
171 let raw =
172 unsafe { libduckdb_sys::duckdb_get_map_value(self.raw, index as libduckdb_sys::idx_t) };
173 (!raw.is_null()).then(|| Self { raw })
174 }
175}