quack_rs/query/chunk.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//! [`OwnedDataChunk`]: a `duckdb_data_chunk` destroyed on drop.
7
8use libduckdb_sys::{
9 duckdb_create_data_chunk, duckdb_data_chunk_reset, duckdb_destroy_data_chunk,
10 duckdb_logical_type, idx_t,
11};
12
13use super::OwnedDataChunk;
14use crate::data_chunk::DataChunk;
15use crate::error::ExtensionError;
16use crate::types::LogicalType;
17
18impl OwnedDataChunk {
19 /// Creates an empty chunk with one column per entry of `types`.
20 ///
21 /// The chunk holds zero rows and has room for [`capacity`][Self::capacity]
22 /// of them. Fill its columns through [`writer`][DataChunk::writer] and
23 /// friends, then [`set_size`][DataChunk::set_size] to the number of rows
24 /// written — for example to build the chunk that
25 /// [`Appender::append_chunk`][crate::appender::Appender::append_chunk]
26 /// takes, without dropping to `duckdb_create_data_chunk`.
27 ///
28 /// `DuckDB` copies the types, so `types` may be dropped as soon as this
29 /// returns.
30 ///
31 /// # Errors
32 ///
33 /// Returns an error, without calling `DuckDB`, if `types` is empty: a chunk
34 /// with no columns trips a debug assertion in `DuckDB`'s
35 /// `DataChunk::Initialize`. Returns an error if `DuckDB` refuses to create
36 /// the chunk, which it does when a type is or contains `ANY` or `INVALID`,
37 /// and when allocating the chunk throws.
38 ///
39 /// # Example
40 ///
41 /// ```rust,no_run
42 /// use quack_rs::query::OwnedDataChunk;
43 /// use quack_rs::types::{LogicalType, TypeId};
44 ///
45 /// # fn demo() -> Result<(), quack_rs::error::ExtensionError> {
46 /// let chunk = OwnedDataChunk::new(&[LogicalType::new(TypeId::BigInt)])?;
47 /// // SAFETY: column 0 is BIGINT and row 0 is within the chunk's capacity.
48 /// unsafe {
49 /// chunk.writer(0).write_i64(0, 42);
50 /// chunk.set_size(1);
51 /// }
52 /// # Ok(())
53 /// # }
54 /// ```
55 pub fn new(types: &[LogicalType]) -> Result<Self, ExtensionError> {
56 if types.is_empty() {
57 return Err(ExtensionError::new(
58 "OwnedDataChunk::new: a data chunk needs at least one column",
59 ));
60 }
61 let mut raw: Vec<duckdb_logical_type> = types.iter().map(LogicalType::as_raw).collect();
62 let count = idx_t::try_from(raw.len())
63 .map_err(|_| ExtensionError::new("OwnedDataChunk::new: too many columns"))?;
64 // SAFETY: `raw` holds `count` live logical types, borrowed from `types`
65 // for the duration of the call. `DuckDB` copies each one into the new
66 // chunk (`types.push_back(*logical_type)`) and keeps no pointer to the
67 // array or to the handles.
68 let chunk = unsafe { duckdb_create_data_chunk(raw.as_mut_ptr(), count) };
69 if chunk.is_null() {
70 return Err(ExtensionError::new(
71 "OwnedDataChunk::new: DuckDB refused to create the chunk; a column type \
72 is or contains ANY or INVALID, or the allocation failed",
73 ));
74 }
75 // SAFETY: `chunk` is non-null, freshly created, and owned by nobody else.
76 Ok(unsafe { Self::from_raw(chunk) })
77 }
78
79 /// The number of rows a chunk made by [`new`][Self::new] has room for:
80 /// `duckdb_vector_size()`, which is 2048 unless `DuckDB` was built with a
81 /// different `STANDARD_VECTOR_SIZE`.
82 ///
83 /// A chunk handed out by [`QueryResult::next_chunk`][super::QueryResult::next_chunk]
84 /// has the same capacity.
85 #[must_use]
86 pub fn capacity(&self) -> usize {
87 usize::try_from(crate::vector::vector_size()).unwrap_or(0)
88 }
89
90 /// Empties the chunk so it can be filled again: its size becomes zero and
91 /// its columns are reset to fresh, writable vectors.
92 ///
93 /// Readers and writers taken from the chunk before the reset must not be
94 /// used after it, since the vectors they point into may have been
95 /// replaced.
96 pub fn reset(&mut self) {
97 // SAFETY: `self.chunk` is a live chunk owned by this value.
98 unsafe { duckdb_data_chunk_reset(self.chunk) };
99 }
100
101 /// Takes ownership of a raw `duckdb_data_chunk`.
102 ///
103 /// # Safety
104 ///
105 /// `chunk` must be a non-null chunk that the caller is responsible for
106 /// destroying, and must not be destroyed by anyone else.
107 #[must_use]
108 pub const unsafe fn from_raw(chunk: libduckdb_sys::duckdb_data_chunk) -> Self {
109 Self {
110 chunk,
111 // SAFETY: `chunk` is valid and outlives the view, which this struct owns.
112 view: unsafe { DataChunk::from_raw(chunk) },
113 }
114 }
115
116 /// Relinquishes ownership, returning the raw handle.
117 ///
118 /// The caller becomes responsible for `duckdb_destroy_data_chunk`.
119 #[must_use]
120 pub const fn into_raw(self) -> libduckdb_sys::duckdb_data_chunk {
121 let raw = self.chunk;
122 std::mem::forget(self);
123 raw
124 }
125}
126
127impl std::fmt::Debug for OwnedDataChunk {
128 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129 // `view` is a borrowing alias of `chunk`; printing it would just repeat
130 // the same pointer.
131 f.debug_struct("OwnedDataChunk")
132 .field("chunk", &self.chunk)
133 .finish_non_exhaustive()
134 }
135}
136
137impl std::ops::Deref for OwnedDataChunk {
138 type Target = DataChunk;
139
140 fn deref(&self) -> &DataChunk {
141 &self.view
142 }
143}
144
145impl Drop for OwnedDataChunk {
146 fn drop(&mut self) {
147 // SAFETY: `self.chunk` was owned by this value and is destroyed once.
148 unsafe { duckdb_destroy_data_chunk(&raw mut self.chunk) };
149 }
150}