Skip to main content

chdb_rust/
query_result.rs

1//! Query result handling for chDB.
2//!
3//! This module provides the [`QueryResult`] type for accessing query execution results.
4
5use core::slice;
6use std::borrow::Cow;
7use std::ffi::CStr;
8use std::time::Duration;
9
10use crate::bindings;
11use crate::error::Error;
12use crate::error::Result;
13
14/// The result of a query execution.
15///
16/// `QueryResult` contains the output data from a query execution, along with
17/// metadata such as execution time and number of rows read.
18///
19/// # Thread Safety
20///
21/// `QueryResult` implements `Send`, meaning it can be safely transferred between threads.
22///
23/// # Examples
24///
25/// ```no_run
26/// use chdb_rust::execute;
27/// use chdb_rust::format::OutputFormat;
28/// use chdb_rust::arg::Arg;
29///
30/// let result = execute(
31///     "SELECT number FROM numbers(10)",
32///     Some(&[Arg::OutputFormat(OutputFormat::JSONEachRow)])
33/// )?;
34///
35/// // Access the data as a string
36/// println!("Data: {}", result.data_utf8_lossy());
37///
38/// // Access metadata
39/// println!("Rows read: {}", result.rows_read());
40/// println!("Bytes read: {}", result.bytes_read());
41/// println!("Elapsed time: {:?}", result.elapsed());
42/// # Ok::<(), chdb_rust::error::Error>(())
43/// ```
44#[derive(Debug)]
45pub struct QueryResult {
46    inner: *mut bindings::chdb_result,
47}
48
49// Safety: QueryResult is safe to send between threads
50// The underlying chDB result structure is thread-safe for read access
51unsafe impl Send for QueryResult {}
52
53impl QueryResult {
54    pub(crate) fn new(inner: *mut bindings::chdb_result) -> Self {
55        Self { inner }
56    }
57
58    /// Get the result data as a UTF-8 string.
59    ///
60    /// This method validates that the data is valid UTF-8. If the data contains
61    /// invalid UTF-8 sequences, it returns an error. It copies the data into a
62    /// new `String`; use [`data_str`](Self::data_str) to borrow it instead.
63    ///
64    /// # Returns
65    ///
66    /// Returns a `String` containing the query result, or an error if the data
67    /// contains invalid UTF-8 sequences.
68    ///
69    /// # Examples
70    ///
71    /// ```no_run
72    /// use chdb_rust::execute;
73    ///
74    /// let result = execute("SELECT 'Hello, World!' AS greeting", None)?;
75    /// let data = result.data_utf8()?;
76    /// println!("{}", data);
77    /// # Ok::<(), chdb_rust::error::Error>(())
78    /// ```
79    ///
80    /// # Errors
81    ///
82    /// Returns [`Error::NonUtf8Sequence`] if the
83    /// result data contains invalid UTF-8 sequences. Use [`data_utf8_lossy`](Self::data_utf8_lossy)
84    /// if you want to handle invalid UTF-8 gracefully.
85    pub fn data_utf8(&self) -> Result<String> {
86        let buf = self.data_ref();
87        String::from_utf8(buf.to_vec()).map_err(Error::NonUtf8Sequence)
88    }
89
90    /// Borrow the result data as a `&str`, without copying it.
91    ///
92    /// The bytes are checked in place, so this is the cheapest way to read a
93    /// text result: nothing is allocated. Use [`data_utf8`](Self::data_utf8) if
94    /// you need an owned `String`.
95    ///
96    /// # Examples
97    ///
98    /// ```no_run
99    /// use chdb_rust::execute;
100    ///
101    /// let result = execute("SELECT 'Hello, World!' AS greeting", None)?;
102    /// let text: &str = result.data_str()?;
103    /// println!("{text}");
104    /// # Ok::<(), chdb_rust::error::Error>(())
105    /// ```
106    ///
107    /// # Errors
108    ///
109    /// Returns [`Error::InvalidUtf8`] if the data is not valid UTF-8, for
110    /// example with a binary output format such as `RowBinary` or `Parquet`.
111    pub fn data_str(&self) -> Result<&str> {
112        std::str::from_utf8(self.data_ref()).map_err(Error::InvalidUtf8)
113    }
114
115    /// Get the result data as a UTF-8 string, replacing invalid sequences.
116    ///
117    /// This method converts the result data to a string, replacing any invalid UTF-8
118    /// sequences with the Unicode replacement character (U+FFFD).
119    ///
120    /// # Returns
121    ///
122    /// Returns a `Cow<str>` containing the query result. Invalid UTF-8 sequences
123    /// are replaced with the replacement character.
124    ///
125    /// # Examples
126    ///
127    /// ```no_run
128    /// use chdb_rust::execute;
129    ///
130    /// let result = execute("SELECT 'Hello, World!' AS greeting", None)?;
131    /// let data = result.data_utf8_lossy();
132    /// println!("{}", data);
133    /// # Ok::<(), chdb_rust::error::Error>(())
134    /// ```
135    pub fn data_utf8_lossy(&self) -> Cow<'_, str> {
136        String::from_utf8_lossy(self.data_ref())
137    }
138
139    /// Get the result data as a UTF-8 string without validation.
140    ///
141    /// # Safety
142    ///
143    /// This function is marked as safe, but it will produce invalid UTF-8 strings
144    /// if the underlying data contains non-UTF-8 bytes. Only use this if you're
145    /// certain the data is valid UTF-8, or if you're prepared to handle potentially
146    /// invalid strings.
147    ///
148    /// # Examples
149    ///
150    /// ```no_run
151    /// use chdb_rust::execute;
152    ///
153    /// let result = execute("SELECT 'Hello' AS greeting", None)?;
154    /// let data = result.data_utf8_unchecked();
155    /// println!("{}", data);
156    /// # Ok::<(), chdb_rust::error::Error>(())
157    /// ```
158    pub fn data_utf8_unchecked(&self) -> String {
159        unsafe { String::from_utf8_unchecked(self.data_ref().to_vec()) }
160    }
161
162    /// Get a reference to the raw result data as bytes.
163    ///
164    /// This method returns a byte slice containing the raw query result data.
165    /// The data is in the format specified when executing the query (e.g., JSON, CSV, etc.).
166    ///
167    /// # Returns
168    ///
169    /// Returns a byte slice containing the query result data. Returns an empty slice
170    /// if there's no data or if the buffer pointer is null.
171    ///
172    /// # Examples
173    ///
174    /// ```no_run
175    /// use chdb_rust::execute;
176    ///
177    /// let result = execute("SELECT 1 AS value", None)?;
178    /// let bytes = result.data_ref();
179    /// println!("Data length: {} bytes", bytes.len());
180    /// # Ok::<(), chdb_rust::error::Error>(())
181    /// ```
182    pub fn data_ref(&self) -> &[u8] {
183        let buf = unsafe { bindings::chdb_result_buffer(self.inner) };
184        let len = unsafe { bindings::chdb_result_length(self.inner) };
185        if buf.is_null() || len == 0 {
186            return &[];
187        }
188        unsafe { slice::from_raw_parts(buf as *const u8, len) }
189    }
190
191    /// Get the number of rows read by the query.
192    ///
193    /// This returns the total number of rows that were read from storage during
194    /// query execution.
195    ///
196    /// # Returns
197    ///
198    /// Returns the number of rows read as a `u64`.
199    ///
200    /// # Examples
201    ///
202    /// ```no_run
203    /// use chdb_rust::execute;
204    ///
205    /// let result = execute("SELECT number FROM numbers(100)", None)?;
206    /// println!("Rows read: {}", result.rows_read());
207    /// # Ok::<(), chdb_rust::error::Error>(())
208    /// ```
209    pub fn rows_read(&self) -> u64 {
210        unsafe { bindings::chdb_result_rows_read(self.inner) }
211    }
212
213    /// Get the number of bytes read by the query.
214    ///
215    /// This returns the total number of bytes that were read from storage during
216    /// query execution.
217    ///
218    /// # Returns
219    ///
220    /// Returns the number of bytes read as a `u64`.
221    ///
222    /// # Examples
223    ///
224    /// ```no_run
225    /// use chdb_rust::execute;
226    ///
227    /// let result = execute("SELECT number FROM numbers(100)", None)?;
228    /// println!("Bytes read: {}", result.bytes_read());
229    /// # Ok::<(), chdb_rust::error::Error>(())
230    /// ```
231    pub fn bytes_read(&self) -> u64 {
232        unsafe { bindings::chdb_result_bytes_read(self.inner) }
233    }
234
235    /// Rows written by the query.
236    ///
237    /// Non-zero for statements that write — `INSERT`, and the result returned
238    /// by [`InsertStream::finish`](crate::insert_stream::InsertStream::finish).
239    /// Wraps `chdb_result_rows_written`.
240    pub fn rows_written(&self) -> u64 {
241        unsafe { bindings::chdb_result_rows_written(self.inner) }
242    }
243
244    /// Bytes written by the query. Wraps `chdb_result_bytes_written`.
245    pub fn bytes_written(&self) -> u64 {
246        unsafe { bindings::chdb_result_bytes_written(self.inner) }
247    }
248
249    /// Rows read from storage, as distinct from rows produced.
250    ///
251    /// [`rows_read`](Self::rows_read) counts what the query pipeline handled;
252    /// this counts what came off disk, so a query answered from an index or a
253    /// projection reports fewer here. Wraps `chdb_result_storage_rows_read`.
254    pub fn storage_rows_read(&self) -> u64 {
255        unsafe { bindings::chdb_result_storage_rows_read(self.inner) }
256    }
257
258    /// Bytes read from storage. Wraps `chdb_result_storage_bytes_read`.
259    pub fn storage_bytes_read(&self) -> u64 {
260        unsafe { bindings::chdb_result_storage_bytes_read(self.inner) }
261    }
262
263    /// Get the elapsed time for query execution.
264    ///
265    /// This returns the time it took to execute the query, measured from when
266    /// the query was submitted until the result was ready.
267    ///
268    /// # Returns
269    ///
270    /// Returns a [`Duration`] representing the elapsed time.
271    ///
272    /// # Examples
273    ///
274    /// ```no_run
275    /// use chdb_rust::execute;
276    ///
277    /// let result = execute("SELECT number FROM numbers(1000)", None)?;
278    /// println!("Query took: {:?}", result.elapsed());
279    /// # Ok::<(), chdb_rust::error::Error>(())
280    /// ```
281    pub fn elapsed(&self) -> Duration {
282        let elapsed = unsafe { bindings::chdb_result_elapsed(self.inner) };
283        Duration::from_secs_f64(elapsed)
284    }
285
286    pub(crate) fn check_error(self) -> Result<Self> {
287        self.check_error_ref()?;
288        Ok(self)
289    }
290
291    pub(crate) fn check_error_ref(&self) -> Result<()> {
292        let err_ptr = unsafe { bindings::chdb_result_error(self.inner) };
293
294        if err_ptr.is_null() {
295            return Ok(());
296        }
297
298        let err_msg = unsafe { CStr::from_ptr(err_ptr).to_string_lossy().to_string() };
299        if err_msg.is_empty() {
300            return Ok(());
301        }
302
303        Err(Error::QueryError(err_msg))
304    }
305}
306
307impl Drop for QueryResult {
308    fn drop(&mut self) {
309        unsafe { bindings::chdb_destroy_query_result(self.inner) };
310    }
311}