Skip to main content

quack_rs/value/
composite.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//! Composite constructors: `STRUCT`, `LIST`, `ARRAY`, `ENUM`, `MAP`, `UNION`.
7
8use libduckdb_sys::duckdb_value;
9
10use super::Value;
11use crate::error::ExtensionError;
12
13impl Value {
14    // ── Composite constructors ───────────────────────────────────────────
15    //
16    // DuckDB *copies* every input value (`UnwrapValue` + `emplace_back` in
17    // `duckdb_value-c.cpp`), so the caller keeps ownership of the children and
18    // they are freed normally when their `Value`s drop.
19
20    /// Creates a `STRUCT` value.
21    ///
22    /// `fields` must line up positionally with `struct_type`'s fields.
23    ///
24    /// # Errors
25    ///
26    /// - The number of `fields` does not match the type's field count. This
27    ///   check is quack-rs's, and it is not cosmetic:
28    ///   `duckdb_create_struct_value` takes **no count argument** and reads
29    ///   `values[0..StructType::GetChildCount(type)]`, so passing a short slice
30    ///   reads past its end.
31    /// - `struct_type` is not a `STRUCT`, or contains an `ANY` / `INVALID` child
32    ///   type — `duckdb_create_struct_value` returns null for those.
33    ///
34    /// # Example
35    ///
36    /// ```rust,no_run
37    /// use quack_rs::types::{LogicalType, TypeId};
38    /// use quack_rs::value::Value;
39    ///
40    /// # fn demo() -> Result<(), quack_rs::error::ExtensionError> {
41    /// let ty = LogicalType::struct_type(&[("x", TypeId::BigInt), ("y", TypeId::Varchar)]);
42    /// let v = Value::struct_value(&ty, &[Value::bigint(1), Value::varchar("two")])?;
43    /// # let _ = v;
44    /// # Ok(())
45    /// # }
46    /// ```
47    pub fn struct_value(
48        struct_type: &crate::types::LogicalType,
49        fields: &[Self],
50    ) -> Result<Self, ExtensionError> {
51        // SAFETY: `struct_type` is a live handle for the duration of the call.
52        let expected = usize::try_from(unsafe { struct_type.struct_child_count() }).unwrap_or(0);
53        if expected != fields.len() {
54            return Err(ExtensionError::new(format!(
55                "Value::struct_value: the type has {expected} field(s) but {} value(s) were \
56                 given; duckdb_create_struct_value reads one value per field and would read \
57                 out of bounds",
58                fields.len()
59            )));
60        }
61        let mut raws: Vec<duckdb_value> = fields.iter().map(Self::as_raw).collect();
62        // SAFETY: `raws` has exactly `expected` entries, which is what DuckDB
63        // reads; every entry is a live handle owned by `fields`, and DuckDB
64        // copies rather than takes them.
65        let raw = unsafe {
66            libduckdb_sys::duckdb_create_struct_value(struct_type.as_raw(), raws.as_mut_ptr())
67        };
68        Self::checked(raw, "duckdb_create_struct_value")
69    }
70
71    /// Creates a `LIST` value from its **element** type.
72    ///
73    /// # `element_type`, not the list type
74    ///
75    /// `duckdb.h` is self-contradictory here: the prose says "Creates a list
76    /// value from a child (element) type", while the `@param` line says "The
77    /// type of the list". The implementation settles it —
78    /// `duckdb_create_list_value` forwards to
79    /// `Value::LIST(const LogicalType &child_type, vector<Value>)`, so it is the
80    /// **element** type, and passing `LogicalType::list(..)` instead makes
81    /// `DuckDB` try to cast every element to a list and return null.
82    ///
83    /// For `LIST<BIGINT>`, pass `LogicalType::new(TypeId::BigInt)`. A list of
84    /// lists is built the same way: for `BIGINT[][]`, pass
85    /// `LogicalType::list(TypeId::BigInt)` and `LIST` items.
86    ///
87    /// # Errors
88    ///
89    /// Returns an error when `duckdb_create_list_value` reports failure: an
90    /// `ANY` or `INVALID` element type, or an item that will not cast to
91    /// `element_type`. When the element type is itself a `LIST`, the error
92    /// also points out the likelier mistake — passing the list type with
93    /// scalar items — since it is the one the header invites.
94    pub fn list_value(
95        element_type: &crate::types::LogicalType,
96        items: &[Self],
97    ) -> Result<Self, ExtensionError> {
98        let mut raws: Vec<duckdb_value> = items.iter().map(Self::as_raw).collect();
99        // SAFETY: the count is passed explicitly and matches `raws`; every entry
100        // is a live handle owned by `items`.
101        let raw = unsafe {
102            libduckdb_sys::duckdb_create_list_value(
103                element_type.as_raw(),
104                raws.as_mut_ptr(),
105                libduckdb_sys::idx_t::try_from(raws.len()).unwrap_or(libduckdb_sys::idx_t::MAX),
106            )
107        };
108        Self::checked_container(
109            raw,
110            element_type,
111            crate::types::TypeId::List,
112            "list_value",
113            "duckdb_create_list_value",
114        )
115    }
116
117    /// Creates an `ARRAY` (fixed-size list) value from its **element** type.
118    ///
119    /// As with [`list_value`][Self::list_value], this is the element type, not
120    /// the array type — `duckdb_create_array_value` forwards to
121    /// `Value::ARRAY(const LogicalType &child_type, vector<Value>)`, which
122    /// *derives* the array type as `ARRAY(child_type, values.size())`. The
123    /// resulting array's size is therefore `items.len()`; there is nothing to
124    /// keep in sync. An array of arrays takes an `ARRAY` element type and
125    /// `ARRAY` items.
126    ///
127    /// # Errors
128    ///
129    /// Returns an error for an empty `items`: an `ARRAY` of size 0 is not a
130    /// type SQL can write (`array_value()` fails with "requires at least one
131    /// argument"), though a release `DuckDB` builds one. Also returns an error
132    /// when `duckdb_create_array_value` reports failure: an `ANY` / `INVALID`
133    /// element type, an item that will not cast to `element_type`, or a length
134    /// at or above `DuckDB`'s maximum array size.
135    pub fn array_value(
136        element_type: &crate::types::LogicalType,
137        items: &[Self],
138    ) -> Result<Self, ExtensionError> {
139        if items.is_empty() {
140            return Err(ExtensionError::new(
141                "Value::array_value: an ARRAY needs at least one element, as in SQL",
142            ));
143        }
144        let mut raws: Vec<duckdb_value> = items.iter().map(Self::as_raw).collect();
145        // SAFETY: as in `list_value`.
146        let raw = unsafe {
147            libduckdb_sys::duckdb_create_array_value(
148                element_type.as_raw(),
149                raws.as_mut_ptr(),
150                libduckdb_sys::idx_t::try_from(raws.len()).unwrap_or(libduckdb_sys::idx_t::MAX),
151            )
152        };
153        Self::checked_container(
154            raw,
155            element_type,
156            crate::types::TypeId::Array,
157            "array_value",
158            "duckdb_create_array_value",
159        )
160    }
161
162    /// Like [`checked`][Self::checked], but when `DuckDB` refused a container
163    /// whose element type is itself `container`, names the likelier cause:
164    /// the "passed the container type instead of the element type" mistake
165    /// that `duckdb.h`'s contradictory `@param` text invites. (A nested
166    /// element type with nested items is legitimate and succeeds.)
167    fn checked_container(
168        raw: duckdb_value,
169        element_type: &crate::types::LogicalType,
170        container: crate::types::TypeId,
171        method: &str,
172        api_func: &'static str,
173    ) -> Result<Self, ExtensionError> {
174        if !raw.is_null() {
175            return Ok(Self { raw });
176        }
177        // SAFETY: `element_type` is a live handle for the duration of the call.
178        let id = unsafe {
179            crate::types::TypeId::try_from_duckdb_type(libduckdb_sys::duckdb_get_type_id(
180                element_type.as_raw(),
181            ))
182        };
183        if id != Some(container) {
184            return Self::checked(raw, api_func);
185        }
186        Err(ExtensionError::new(format!(
187            "Value::{method} takes the *element* type, and {api_func} could not cast the items \
188             to the {sql} element type given. If you passed the {sql} type itself, pass the type \
189             of one item instead (duckdb.h's prose says \"child (element) type\" while its \
190             @param line says \"the type of the {lower}\"; the implementation takes the element \
191             type). For a {lower} of {lower}s, every item must itself be a {sql}.",
192            sql = container.sql_name(),
193            lower = container.sql_name().to_lowercase()
194        )))
195    }
196
197    /// Creates an `ENUM` value from its dictionary index.
198    ///
199    /// # Errors
200    ///
201    /// Returns an error when `enum_type` is not an `ENUM` or `index` is outside
202    /// its dictionary.
203    pub fn enum_value(
204        enum_type: &crate::types::LogicalType,
205        index: u64,
206    ) -> Result<Self, ExtensionError> {
207        // SAFETY: `enum_type` is a live handle for the duration of the call.
208        let raw = unsafe { libduckdb_sys::duckdb_create_enum_value(enum_type.as_raw(), index) };
209        Self::checked(raw, "duckdb_create_enum_value")
210    }
211
212    /// Wraps a possibly-null constructor result, naming the C function that
213    /// produced it.
214    pub(super) fn checked(
215        raw: duckdb_value,
216        api_func: &'static str,
217    ) -> Result<Self, ExtensionError> {
218        if raw.is_null() {
219            return Err(ExtensionError::new(format!(
220                "{api_func} returned null: the logical type and the supplied values do not \
221                 form a valid value (check the type's kind, its child types, and the value count)"
222            )));
223        }
224        Ok(Self { raw })
225    }
226
227    /// Creates a `MAP` value from parallel key and value slices.
228    ///
229    /// Named `map` rather than `map_value` because
230    /// [`map_value`][Self::map_value] is already the accessor that reads the
231    /// value of the `index`-th entry.
232    ///
233    /// `map_type` is the `MAP` type itself. Requires `duckdb-1-5`:
234    /// `duckdb_create_map_value` sits in the unstable region of the C API
235    /// struct.
236    ///
237    /// # Errors
238    ///
239    /// Returns an error when the slices differ in length, or when
240    /// `duckdb_create_map_value` reports failure — `map_type` is not a `MAP`,
241    /// a child type is `ANY` / `INVALID`, or a key repeats.
242    #[cfg(feature = "duckdb-1-5")]
243    pub fn map(
244        map_type: &crate::types::LogicalType,
245        keys: &[Self],
246        values: &[Self],
247    ) -> Result<Self, ExtensionError> {
248        if keys.len() != values.len() {
249            return Err(ExtensionError::new(format!(
250                "Value::map: {} key(s) but {} value(s)",
251                keys.len(),
252                values.len()
253            )));
254        }
255        let mut key_raws: Vec<duckdb_value> = keys.iter().map(Self::as_raw).collect();
256        let mut val_raws: Vec<duckdb_value> = values.iter().map(Self::as_raw).collect();
257        // SAFETY: both slices have exactly `entry_count` live handles, checked
258        // equal above; DuckDB copies rather than takes them.
259        let raw = unsafe {
260            libduckdb_sys::duckdb_create_map_value(
261                map_type.as_raw(),
262                key_raws.as_mut_ptr(),
263                val_raws.as_mut_ptr(),
264                libduckdb_sys::idx_t::try_from(key_raws.len()).unwrap_or(libduckdb_sys::idx_t::MAX),
265            )
266        };
267        Self::checked(raw, "duckdb_create_map_value")
268    }
269
270    /// Creates a `UNION` value for the member at `tag_index`.
271    ///
272    /// Requires `duckdb-1-5`: `duckdb_create_union_value` sits in the unstable
273    /// region of the C API struct.
274    ///
275    /// # Errors
276    ///
277    /// Returns an error when `union_type` is not a `UNION`, `tag_index` is out
278    /// of range, or `value`'s type does not equal that member's declared type —
279    /// `DuckDB` compares them exactly and returns null on a mismatch.
280    #[cfg(feature = "duckdb-1-5")]
281    pub fn union_value(
282        union_type: &crate::types::LogicalType,
283        tag_index: u64,
284        value: &Self,
285    ) -> Result<Self, ExtensionError> {
286        // SAFETY: both handles are live for the duration of the call, and
287        // DuckDB copies the value rather than taking it.
288        let raw = unsafe {
289            libduckdb_sys::duckdb_create_union_value(union_type.as_raw(), tag_index, value.as_raw())
290        };
291        Self::checked(raw, "duckdb_create_union_value")
292    }
293}