quack_rs/query/result.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 a [`QueryResult`]: its columns, its chunks and what kind of outcome it is.
7
8use libduckdb_sys::{
9 duckdb_column_count, duckdb_column_name, duckdb_column_type, duckdb_destroy_result,
10 duckdb_fetch_chunk, duckdb_result, duckdb_result_error, duckdb_rows_changed, idx_t,
11};
12
13use super::cstr::c_str_to_owned;
14use super::{FetchState, OwnedDataChunk, QueryResult, ResultKind};
15use crate::error::ExtensionError;
16use crate::types::TypeId;
17
18impl QueryResult {
19 /// Number of columns in the result.
20 #[must_use]
21 pub fn column_count(&self) -> usize {
22 let mut result = self.result;
23 // SAFETY: `result` is a valid materialised result; the C API takes a
24 // mutable pointer but does not mutate observable state here.
25 usize::try_from(unsafe { duckdb_column_count(&raw mut result) }).unwrap_or(0)
26 }
27
28 /// Name of column `index`, or `None` if the index is out of range or the
29 /// name is not UTF-8.
30 #[must_use]
31 pub fn column_name(&self, index: usize) -> Option<String> {
32 if index >= self.column_count() {
33 return None;
34 }
35 let mut result = self.result;
36 // SAFETY: `index` was bounds-checked against `column_count`.
37 let ptr = unsafe { duckdb_column_name(&raw mut result, index as idx_t) };
38 // SAFETY: DuckDB returns a NUL-terminated string owned by the result.
39 unsafe { c_str_to_owned(ptr) }
40 }
41
42 /// [`TypeId`] of column `index`, or `None` if the index is out of range or
43 /// the type is one this build does not recognise.
44 #[must_use]
45 pub fn column_type(&self, index: usize) -> Option<TypeId> {
46 if index >= self.column_count() {
47 return None;
48 }
49 let mut result = self.result;
50 // SAFETY: `index` was bounds-checked against `column_count`.
51 let raw = unsafe { duckdb_column_type(&raw mut result, index as idx_t) };
52 TypeId::try_from_duckdb_type(raw)
53 }
54
55 /// Rows changed by an `INSERT` / `UPDATE` / `DELETE`. Zero for other
56 /// statements.
57 #[must_use]
58 pub fn rows_changed(&self) -> u64 {
59 let mut result = self.result;
60 // SAFETY: `result` is a valid materialised result.
61 unsafe { duckdb_rows_changed(&raw mut result) }
62 }
63
64 /// Fetches the next chunk of rows: `Ok(None)` once every row has been
65 /// read, `Err` if the rows stopped early.
66 ///
67 /// Chunks hold at most `duckdb_vector_size()` rows; call this repeatedly:
68 ///
69 /// ```rust,no_run
70 /// # fn demo(mut result: quack_rs::query::QueryResult) -> Result<(), quack_rs::error::ExtensionError> {
71 /// while let Some(chunk) = result.next_chunk()? {
72 /// // ... read chunk.size() rows ...
73 /// # let _ = chunk;
74 /// }
75 /// # Ok(())
76 /// # }
77 /// ```
78 ///
79 /// # Errors
80 ///
81 /// `duckdb_fetch_chunk` returns null both at the end of the rows and when
82 /// fetching fails, recording the failure on the result. On a **streaming**
83 /// result that happens when execution fails part-way (a runtime error in
84 /// the query, an interrupt) or, up to `DuckDB` 1.5.x, when another
85 /// statement has run on the same connection, which invalidates the stream
86 /// (2.0.0 refuses that statement instead; see
87 /// `PreparedStatement::execute_streaming`).
88 /// This returns that error — with
89 /// `DuckDB`'s message — instead of reporting a clean end after a partial
90 /// result. Once it has returned `Ok(None)` or an error it keeps returning
91 /// the same thing without calling `DuckDB` again.
92 pub fn next_chunk(&mut self) -> Result<Option<OwnedDataChunk>, ExtensionError> {
93 match &self.fetch {
94 FetchState::Open => {}
95 FetchState::Ended => return Ok(None),
96 FetchState::Failed(message) => return Err(ExtensionError::new(message.clone())),
97 }
98 // SAFETY: `duckdb_fetch_chunk` takes the result by value (it reads the
99 // internal pointer) and returns a chunk the caller owns, or null when
100 // there are no more rows or fetching failed.
101 let chunk = unsafe { duckdb_fetch_chunk(self.result) };
102 if !chunk.is_null() {
103 // SAFETY: `chunk` is non-null and owned by us from here on.
104 return Ok(Some(unsafe { OwnedDataChunk::from_raw(chunk) }));
105 }
106 // `duckdb_fetch_chunk` catches a failed `Fetch` and records it with
107 // `QueryResult::SetError`; a clean end records nothing.
108 // SAFETY: `self.result` is a live result owned by this value.
109 let error = unsafe { c_str_to_owned(duckdb_result_error(&raw mut self.result)) };
110 self.fetch = error.map_or(FetchState::Ended, |message| {
111 FetchState::Failed(format!(
112 "the result ended early: fetching the next chunk failed: {message}"
113 ))
114 });
115 self.next_chunk()
116 }
117
118 /// Returns the full [`LogicalType`][crate::types::LogicalType] of column
119 /// `index`.
120 ///
121 /// [`column_type`][Self::column_type] collapses a column to its top-level
122 /// [`TypeId`], which is all you need for a scalar but
123 /// loses everything about a `STRUCT`'s fields, a `LIST`'s element type, a
124 /// `DECIMAL`'s width and scale, or an `ENUM`'s dictionary. This keeps them.
125 ///
126 /// Returns `None` when `index` is out of range.
127 #[must_use]
128 pub fn column_logical_type(&self, index: usize) -> Option<crate::types::LogicalType> {
129 if index >= self.column_count() {
130 return None;
131 }
132 let mut result = self.result;
133 // SAFETY: `result` is a valid materialised result and `index` is in range.
134 let raw =
135 unsafe { libduckdb_sys::duckdb_column_logical_type(&raw mut result, index as idx_t) };
136 if raw.is_null() {
137 return None;
138 }
139 // SAFETY: `duckdb_column_logical_type` returns a handle the caller owns
140 // and must destroy; `LogicalType` does that on drop.
141 Some(unsafe { crate::types::LogicalType::from_raw(raw) })
142 }
143
144 /// What kind of outcome the statement produced.
145 #[must_use]
146 pub fn result_kind(&self) -> ResultKind {
147 // SAFETY: `duckdb_result_return_type` takes the result by value and
148 // only reads it.
149 let raw = unsafe { libduckdb_sys::duckdb_result_return_type(self.result) };
150 match raw {
151 libduckdb_sys::duckdb_result_type_DUCKDB_RESULT_TYPE_QUERY_RESULT => ResultKind::Rows,
152 libduckdb_sys::duckdb_result_type_DUCKDB_RESULT_TYPE_CHANGED_ROWS => {
153 ResultKind::ChangedRows
154 }
155 libduckdb_sys::duckdb_result_type_DUCKDB_RESULT_TYPE_NOTHING => ResultKind::Nothing,
156 _ => ResultKind::Invalid,
157 }
158 }
159
160 /// Whether this result is streaming rather than fully materialised.
161 ///
162 /// Only [`PreparedStatement::execute_streaming`][super::PreparedStatement::execute_streaming] can produce a streaming
163 /// result, and even then `DuckDB` may decide to materialise — which is why
164 /// this is a question rather than a guarantee.
165 ///
166 /// Requires `duckdb-1-5`: `duckdb_result_is_streaming` sits in the unstable
167 /// region of the C API struct.
168 #[cfg(feature = "duckdb-1-5")]
169 #[must_use]
170 pub fn is_streaming(&self) -> bool {
171 // SAFETY: `duckdb_result_is_streaming` takes the result by value and
172 // only reads it.
173 unsafe { libduckdb_sys::duckdb_result_is_streaming(self.result) }
174 }
175
176 /// The Arrow production settings this result was created with
177 /// (`duckdb_result_get_arrow_options`).
178 ///
179 /// Hand these to
180 /// [`arrow::to_arrow_schema`][crate::arrow::to_arrow_schema] and
181 /// [`arrow::data_chunk_to_arrow`][crate::arrow::data_chunk_to_arrow] when
182 /// exporting this result's chunks: they carry the client properties captured
183 /// when the query ran, which is what the chunks were built against.
184 ///
185 /// # Errors
186 ///
187 /// Returns an [`ExtensionError`] when `DuckDB` returns null, which it does
188 /// for a result with no internal data.
189 ///
190 /// # Safety
191 ///
192 /// The connection that ran this query must stay open for all of `'conn`:
193 /// the options point at its `ClientContext`, and a `QueryResult` does not
194 /// borrow its connection. See
195 /// [`ArrowOptions::from_result`][crate::arrow::ArrowOptions::from_result].
196 /// [`ArrowOptions::from_connection`][crate::arrow::ArrowOptions::from_connection]
197 /// is the safe alternative.
198 #[cfg(feature = "duckdb-1-5-4")]
199 pub unsafe fn arrow_options<'conn>(
200 &self,
201 ) -> Result<crate::arrow::ArrowOptions<'conn>, ExtensionError> {
202 // SAFETY: forwarded verbatim from this function's contract.
203 unsafe { crate::arrow::ArrowOptions::from_result(self) }
204 }
205
206 /// Returns the raw `duckdb_result`.
207 ///
208 /// Use this for C API calls this crate does not wrap. Do not destroy it —
209 /// this value still owns it.
210 #[must_use]
211 pub const fn as_raw(&self) -> &duckdb_result {
212 &self.result
213 }
214
215 /// Takes ownership of a raw `duckdb_result`, which is then destroyed
216 /// (`duckdb_destroy_result`) on drop: the way back into this crate's
217 /// RAII for a result a raw call filled in (`duckdb_execute_pending`, for
218 /// one).
219 ///
220 /// # Safety
221 ///
222 /// `result` must have been filled in by a successful `DuckDB` call
223 /// (`duckdb_query`, `duckdb_execute_prepared`, `duckdb_execute_pending`,
224 /// …) and must not be destroyed by anyone else. Its connection must stay
225 /// open while it is read. Chunks already fetched from it are not seen
226 /// again: [`next_chunk`][Self::next_chunk] continues where the raw
227 /// fetching stopped.
228 ///
229 /// # Example
230 ///
231 /// ```rust,no_run
232 /// use quack_rs::query::QueryResult;
233 ///
234 /// # unsafe fn demo(con: libduckdb_sys::duckdb_connection) {
235 /// // SAFETY: zeroed is a valid `duckdb_result`; DuckDB fills it in.
236 /// let mut raw: libduckdb_sys::duckdb_result = unsafe { std::mem::zeroed() };
237 /// // SAFETY: `con` is open.
238 /// let state = unsafe { libduckdb_sys::duckdb_query(con, c"SELECT 1".as_ptr(), &raw mut raw) };
239 /// if state == libduckdb_sys::DuckDBSuccess {
240 /// // SAFETY: filled in by a successful `duckdb_query`, owned by nothing else.
241 /// let result = unsafe { QueryResult::from_raw(raw) };
242 /// assert_eq!(result.column_count(), 1);
243 /// }
244 /// # }
245 /// ```
246 #[must_use]
247 pub const unsafe fn from_raw(result: duckdb_result) -> Self {
248 Self::new(result)
249 }
250
251 /// Gives up ownership and returns the raw result, which the caller must
252 /// destroy (`duckdb_destroy_result`) or hand back to
253 /// [`from_raw`][Self::from_raw]. Whether [`next_chunk`][Self::next_chunk]
254 /// had reached the end is not carried over.
255 #[must_use]
256 pub const fn into_raw(self) -> duckdb_result {
257 let raw = self.result;
258 std::mem::forget(self);
259 raw
260 }
261}
262
263impl std::fmt::Debug for QueryResult {
264 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265 // Deliberately does not call into DuckDB: `Debug` is often reached from
266 // panic/assertion paths where an extra FFI call is unhelpful.
267 f.debug_struct("QueryResult").finish_non_exhaustive()
268 }
269}
270
271impl Drop for QueryResult {
272 fn drop(&mut self) {
273 // SAFETY: `self.result` was populated by DuckDB and is destroyed once.
274 unsafe { duckdb_destroy_result(&raw mut self.result) };
275 }
276}