chdb-rust 2.1.0

chDB FFI bindings for Rust(Experimental)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Streaming query result handling for chDB.
//!
//! This module provides the [`QueryStream`] type for reading large query results
//! in chunks without materializing the entire output in memory.

use std::mem::ManuallyDrop;
use std::os::raw::c_char;

use crate::bindings;
use crate::connection::Connection;
use crate::error::{Error, Result};
use crate::format::OutputFormat;
use crate::query_param::{EncodedParams, QueryParams};
use crate::query_result::QueryResult;

enum QueryStreamConnection<'a> {
    Borrowed(&'a mut Connection),
    Owned(Connection),
}

/// A streaming query result that yields data in chunks.
///
/// `QueryStream` is returned by [`Connection::query_stream`](crate::connection::Connection::query_stream),
/// [`Connection::query_stream_with_params`](crate::connection::Connection::query_stream_with_params),
/// [`Session::execute_stream`](crate::session::Session::execute_stream),
/// [`Session::execute_stream_with_params`](crate::session::Session::execute_stream_with_params),
/// [`execute_stream`](crate::execute_stream), and
/// [`execute_stream_with_params`](crate::execute_stream_with_params). Each chunk is a [`QueryResult`] that the caller owns
/// and must drop before requesting the next chunk.
///
/// `QueryStream` also implements [`Iterator`], so you can collect chunks with adapter methods
/// such as [`Iterator::collect`].
///
/// # Thread Safety
///
/// While a borrowed stream is active, its [`Connection`]
/// is exclusively borrowed and cannot be used for other queries. This prevents concurrent
/// access to a non-[`Sync`] handle. Streams from [`execute_stream`](crate::execute_stream)
/// own their connection outright.
///
/// # Examples
///
/// ```no_run
/// use chdb_rust::connection::Connection;
/// use chdb_rust::format::OutputFormat;
///
/// let mut conn = Connection::open_in_memory()?;
/// let mut stream = conn.query_stream(
///     "SELECT number FROM numbers(100_000)",
///     OutputFormat::JSONEachRow,
/// )?;
///
/// while let Some(chunk) = stream.next_chunk()? {
///     print!("{}", chunk.data_utf8_lossy());
/// }
/// # Ok::<(), chdb_rust::error::Error>(())
/// ```
pub struct QueryStream<'a> {
    conn: QueryStreamConnection<'a>,
    stream: *mut bindings::chdb_result,
    finished: bool,
}

impl<'a> QueryStream<'a> {
    pub(crate) fn start_borrowed(
        conn: &'a mut Connection,
        sql: &str,
        format: OutputFormat,
    ) -> Result<Self> {
        let stream = Self::start_query(conn.handle(), sql, format)?;
        Ok(Self {
            conn: QueryStreamConnection::Borrowed(conn),
            stream,
            finished: false,
        })
    }

    pub(crate) fn start_owned(conn: Connection, sql: &str, format: OutputFormat) -> Result<Self> {
        let stream = Self::start_query(conn.handle(), sql, format)?;
        Ok(Self {
            conn: QueryStreamConnection::Owned(conn),
            stream,
            finished: false,
        })
    }

    pub(crate) fn start_borrowed_with_params(
        conn: &'a mut Connection,
        sql: &str,
        format: OutputFormat,
        params: impl Into<QueryParams>,
    ) -> Result<Self> {
        let stream = Self::start_query_with_params(conn.handle(), sql, format, params)?;
        Ok(Self {
            conn: QueryStreamConnection::Borrowed(conn),
            stream,
            finished: false,
        })
    }

    pub(crate) fn start_owned_with_params(
        conn: Connection,
        sql: &str,
        format: OutputFormat,
        params: impl Into<QueryParams>,
    ) -> Result<Self> {
        let stream = Self::start_query_with_params(conn.handle(), sql, format, params)?;
        Ok(Self {
            conn: QueryStreamConnection::Owned(conn),
            stream,
            finished: false,
        })
    }

    fn start_query(
        conn: bindings::chdb_connection,
        sql: &str,
        format: OutputFormat,
    ) -> Result<*mut bindings::chdb_result> {
        let format = format.as_str();
        // chdb_stream_query_n takes pointer + length for both strings, so
        // neither has to be NUL-terminated. It returns an owned streaming
        // chdb_result handle (or null on failure) that the caller must both
        // cancel with chdb_stream_cancel_query and free with
        // chdb_destroy_query_result once done — QueryStream::cancel (called
        // from Drop) does both. `check_start`, below, probes the handle for a
        // start-up error without taking ownership of it.
        let stream_ptr = unsafe {
            bindings::chdb_stream_query_n(
                conn,
                sql.as_ptr() as *const c_char,
                sql.len(),
                format.as_ptr() as *const c_char,
                format.len(),
            )
        };

        Self::check_start(stream_ptr)
    }

    /// A non-null stream handle may still carry an initialisation error, so the
    /// handle is probed once before it is handed out. The probe must not free
    /// the handle on the success path, hence the `ManuallyDrop` dance.
    fn check_start(stream_ptr: *mut bindings::chdb_result) -> Result<*mut bindings::chdb_result> {
        if stream_ptr.is_null() {
            return Err(Error::NoResult);
        }

        let probe = ManuallyDrop::new(QueryResult::new(stream_ptr));
        if let Err(e) = probe.check_error_ref() {
            drop(ManuallyDrop::into_inner(probe));
            return Err(e);
        }
        std::mem::forget(ManuallyDrop::into_inner(probe));

        Ok(stream_ptr)
    }

    fn start_query_with_params(
        conn: bindings::chdb_connection,
        sql: &str,
        format: OutputFormat,
        params: impl Into<QueryParams>,
    ) -> Result<*mut bindings::chdb_result> {
        let format = format.as_str();
        let encoded = EncodedParams::encode(params)?;

        // chdb_stream_query_with_params_n takes pointer + length for query,
        // format, and each bound value. It returns an owned streaming
        // chdb_result handle (or null on failure) that QueryStream::cancel
        // (called from Drop) cancels and frees.
        let stream_ptr = unsafe {
            bindings::chdb_stream_query_with_params_n(
                conn,
                sql.as_ptr() as *const c_char,
                sql.len(),
                format.as_ptr() as *const c_char,
                format.len(),
                encoded.names_ptr(),
                encoded.name_lens_ptr(),
                encoded.values_ptr(),
                encoded.value_lens_ptr(),
                encoded.len(),
            )
        };

        Self::check_start(stream_ptr)
    }

    fn conn_handle(&self) -> bindings::chdb_connection {
        match &self.conn {
            QueryStreamConnection::Borrowed(conn) => conn.handle(),
            QueryStreamConnection::Owned(conn) => conn.handle(),
        }
    }

    /// Fetch the next chunk of query results.
    ///
    /// Each call returns one chunk of output in the format specified when the stream was
    /// started. Drop the previous chunk before calling this method again.
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(chunk))` while data remains, or `Ok(None)` once the stream is
    /// exhausted. Each returned chunk is an independent [`QueryResult`] that is freed
    /// when dropped.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::connection::Connection;
    /// use chdb_rust::format::OutputFormat;
    ///
    /// let mut conn = Connection::open_in_memory()?;
    /// let mut stream = conn.query_stream(
    ///     "SELECT number FROM numbers(10)",
    ///     OutputFormat::JSONEachRow,
    /// )?;
    ///
    /// while let Some(chunk) = stream.next_chunk()? {
    ///     println!("rows in chunk: {}", chunk.rows_read());
    /// }
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The underlying fetch call fails
    /// - A chunk contains a query error
    pub fn next_chunk(&mut self) -> Result<Option<QueryResult>> {
        if self.finished || self.stream.is_null() {
            return Ok(None);
        }

        let chunk_ptr =
            unsafe { bindings::chdb_stream_fetch_result(self.conn_handle(), self.stream) };

        if chunk_ptr.is_null() {
            self.finished = true;
            return Err(Error::NoResult);
        }

        let chunk = QueryResult::new(chunk_ptr);

        if let Err(e) = chunk.check_error_ref() {
            self.finished = true;
            return Err(e);
        }

        if chunk.rows_read() == 0 {
            drop(chunk);
            self.finished = true;
            return Ok(None);
        }

        Ok(Some(chunk))
    }

    /// Cancel the streaming query and release resources.
    ///
    /// Stops the query on the server and frees the stream handle. After cancellation,
    /// further calls to [`next_chunk`](Self::next_chunk) return `Ok(None)`.
    ///
    /// This is called automatically when the stream is dropped. Call this explicitly to
    /// stop early without waiting for the stream to be dropped.
    pub fn cancel(&mut self) {
        if self.stream.is_null() {
            return;
        }

        let conn = self.conn_handle();
        unsafe {
            if !self.finished {
                bindings::chdb_stream_cancel_query(conn, self.stream);
            }
            bindings::chdb_destroy_query_result(self.stream);
        }
        self.stream = std::ptr::null_mut();
        self.finished = true;
    }
}

impl<'a> Iterator for QueryStream<'a> {
    type Item = Result<QueryResult>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.next_chunk() {
            Ok(Some(chunk)) => Some(Ok(chunk)),
            Ok(None) => None,
            Err(err) => Some(Err(err)),
        }
    }
}

impl Drop for QueryStream<'_> {
    fn drop(&mut self) {
        if !self.stream.is_null() {
            self.cancel();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::ffi::CString;

    use super::*;
    use crate::bindings;
    use crate::session::SessionBuilder;
    use crate::test_utils::tempdir;

    #[test]
    fn test_large_stream_row_count_and_chunking() -> Result<()> {
        const ROWS: u64 = 100_000;
        let mut conn = Connection::open_in_memory()?;
        let mut stream = conn.query_stream(
            &format!("SELECT number FROM numbers({ROWS})"),
            OutputFormat::JSONEachRow,
        )?;

        let mut chunks = 0usize;
        let mut rows = 0u64;
        while let Some(chunk) = stream.next_chunk()? {
            chunks += 1;
            rows += chunk.rows_read();
        }

        assert_eq!(rows, ROWS, "streamed row count should match query size");
        assert!(
            chunks > 1,
            "expected multiple chunks for large result set, got {chunks}"
        );
        Ok(())
    }

    #[test]
    fn test_large_stream_matches_materialized_query() -> Result<()> {
        use crate::arg::Arg;
        use crate::execute;

        const ROWS: u64 = 100_000;
        let query = format!("SELECT number FROM numbers({ROWS})");
        let args = Some(&[Arg::OutputFormat(OutputFormat::JSONEachRow)] as &[Arg]);

        let materialized = execute(&query, args)?;
        let mut streamed = String::new();
        let mut conn = Connection::open_in_memory()?;
        let mut stream = conn.query_stream(&query, OutputFormat::JSONEachRow)?;
        while let Some(chunk) = stream.next_chunk()? {
            streamed.push_str(&chunk.data_utf8_lossy());
        }

        assert_eq!(streamed, materialized.data_utf8_lossy());
        Ok(())
    }

    #[test]
    fn test_raw_stream_ffi_matches_c() -> Result<()> {
        let conn = Connection::open_in_memory()?;
        let query = CString::new("SELECT number FROM numbers(5)")?;
        let format = CString::new("JSONEachRow")?;

        let stream =
            unsafe { bindings::chdb_stream_query(conn.handle(), query.as_ptr(), format.as_ptr()) };
        assert!(!stream.is_null());

        let chunk = unsafe { bindings::chdb_stream_fetch_result(conn.handle(), stream) };
        assert!(!chunk.is_null(), "fetch returned null");

        let result = QueryResult::new(chunk);
        result.check_error_ref()?;
        assert_eq!(result.rows_read(), 5);
        assert!(result.data_utf8_lossy().contains("\"number\":0"));

        unsafe {
            bindings::chdb_stream_cancel_query(conn.handle(), stream);
            bindings::chdb_destroy_query_result(stream);
        }
        Ok(())
    }

    #[test]
    fn test_execute_stream_matches_query() -> Result<()> {
        use crate::arg::Arg;
        use crate::execute;
        use crate::execute_stream;

        let query = "SELECT number FROM numbers(10)";
        let args = Some(&[Arg::OutputFormat(OutputFormat::JSONEachRow)] as &[Arg]);

        let materialized = execute(query, args)?;
        let mut streamed = String::new();
        let mut stream = execute_stream(query, args)?;
        while let Some(chunk) = stream.next_chunk()? {
            streamed.push_str(&chunk.data_utf8_lossy());
        }

        assert_eq!(streamed, materialized.data_utf8_lossy());
        Ok(())
    }

    #[test]
    fn test_query_stream_basic() -> Result<()> {
        let mut conn = Connection::open_in_memory()?;
        let mut stream =
            conn.query_stream("SELECT number FROM numbers(5)", OutputFormat::JSONEachRow)?;

        let mut chunks = Vec::new();
        while let Some(chunk) = stream.next_chunk()? {
            chunks.push(chunk.data_utf8_lossy().to_string());
        }

        let combined: String = chunks.concat();
        assert!(combined.contains("\"number\":0"));
        assert!(combined.contains("\"number\":4"));
        Ok(())
    }

    #[test]
    fn test_query_stream_iterator() -> Result<()> {
        let mut conn = Connection::open_in_memory()?;
        let stream = conn.query_stream("SELECT 1 AS a UNION ALL SELECT 2", OutputFormat::CSV)?;

        let chunks: Vec<_> = stream.collect::<Result<Vec<_>>>()?;
        assert!(!chunks.is_empty());
        Ok(())
    }

    #[test]
    fn test_query_stream_error_then_retry_returns_none() -> Result<()> {
        let mut conn = Connection::open_in_memory()?;
        let mut stream =
            conn.query_stream("SELECT * FROM nonexistent_table", OutputFormat::JSONEachRow)?;

        assert!(stream.next_chunk().is_err());
        assert!(stream.next_chunk()?.is_none());
        Ok(())
    }

    #[test]
    fn test_query_stream_syntax_error_fails_at_start() -> Result<()> {
        let mut conn = Connection::open_in_memory()?;
        let result = conn.query_stream("SELECT invalid syntax here", OutputFormat::JSONEachRow);
        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn test_query_stream_with_params_error_then_retry_returns_none() -> Result<()> {
        let mut conn = Connection::open_in_memory()?;
        let mut stream = conn.query_stream_with_params(
            "SELECT * FROM nonexistent_table WHERE id = {id:UInt64}",
            OutputFormat::JSONEachRow,
            [("id", 1_u64)],
        )?;

        assert!(stream.next_chunk().is_err());
        assert!(stream.next_chunk()?.is_none());
        Ok(())
    }

    #[test]
    fn test_query_stream_with_params_syntax_error_fails_at_start() -> Result<()> {
        let mut conn = Connection::open_in_memory()?;
        let result = conn.query_stream_with_params(
            "SELECT invalid syntax here",
            OutputFormat::JSONEachRow,
            [("x", 1_u64)],
        );
        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn test_session_execute_stream() -> Result<()> {
        let tmp = tempdir();
        let mut session = SessionBuilder::new()
            .with_data_path(tmp.path())
            .with_auto_cleanup(true)
            .build()?;

        session.execute(
            "CREATE TABLE items (id UInt64) ENGINE = MergeTree() ORDER BY id",
            None,
        )?;
        session.execute("INSERT INTO items VALUES (1), (2), (3)", None)?;

        let mut stream = session.execute_stream("SELECT * FROM items", None)?;
        let mut total_rows = 0usize;
        while let Some(chunk) = stream.next_chunk()? {
            total_rows += chunk.data_ref().iter().filter(|&&b| b == b'\n').count();
        }

        assert_eq!(total_rows, 3);
        Ok(())
    }
}