chdb-rust 2.2.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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! Arrow C Data Interface batch streaming for chDB query results.
//!
//! This module wraps `chdb_stream_query_arrow` / `chdb_stream_fetch_arrow` and
//! yields [`arrow::record_batch::RecordBatch`] values one engine block at a time,
//! without Arrow IPC serialization.
//!
//! Available when the crate is built with the `arrow` feature.

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

use arrow::array::RecordBatchReader;
use arrow::ffi::{FFI_ArrowArray, FFI_ArrowSchema};
use arrow::ffi_stream::{ArrowArrayStreamReader, FFI_ArrowArrayStream};
use arrow::record_batch::RecordBatch;

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

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

/// A one-shot Arrow reader over a query's entire result.
///
/// Returned by [`Connection::query_arrow`](crate::connection::Connection::query_arrow)
/// and [`Connection::query_arrow_with_opts`](crate::connection::Connection::query_arrow_with_opts).
///
/// The C ABI transfers ownership of the stream's `release` callback to the
/// caller. The engine materializes a standalone Arrow table, so this reader
/// does not borrow the [`Connection`] that produced it and can be drained
/// after that connection is dropped.
pub struct ArrowReader {
    inner: ArrowArrayStreamReader,
}

impl ArrowReader {
    pub(crate) fn new(inner: ArrowArrayStreamReader) -> Self {
        Self { inner }
    }
}

impl Iterator for ArrowReader {
    type Item = arrow::error::Result<RecordBatch>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

impl arrow::array::RecordBatchReader for ArrowReader {
    fn schema(&self) -> arrow::datatypes::SchemaRef {
        self.inner.schema()
    }
}

/// A streaming Arrow query that yields [`RecordBatch`] values one block at a time.
///
/// Batches come from the Arrow C Data Interface (no Arrow IPC). Create a stream from a
/// [`Connection`], [`Session`](crate::session::Session), or the crate-level
/// `execute_stream_arrow*` helpers. Implements [`Iterator`].
///
/// # 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_arrow`](crate::execute_stream_arrow)
/// own their connection outright.
pub struct ArrowQueryStream<'a> {
    conn: ArrowQueryStreamConnection<'a>,
    inner: *mut bindings::chdb_result,
    finished: bool,
    schema: Option<arrow::datatypes::SchemaRef>,
}

impl<'a> ArrowQueryStream<'a> {
    pub(crate) fn start_borrowed(
        conn: &'a mut Connection,
        sql: &str,
        opts: Option<&ArrowOptions>,
    ) -> Result<Self> {
        let inner = Self::start_query(conn.handle(), sql, opts)?;
        Ok(Self {
            conn: ArrowQueryStreamConnection::Borrowed(conn),
            inner,
            finished: false,
            schema: None,
        })
    }

    pub(crate) fn start_owned(
        conn: Connection,
        sql: &str,
        opts: Option<&ArrowOptions>,
    ) -> Result<Self> {
        let inner = Self::start_query(conn.handle(), sql, opts)?;
        Ok(Self {
            conn: ArrowQueryStreamConnection::Owned(conn),
            inner,
            finished: false,
            schema: None,
        })
    }

    pub(crate) fn start_borrowed_with_params(
        conn: &'a mut Connection,
        sql: &str,
        params: impl Into<QueryParams>,
        opts: Option<&ArrowOptions>,
    ) -> Result<Self> {
        let inner = Self::start_query_with_params(conn.handle(), sql, params, opts)?;
        Ok(Self {
            conn: ArrowQueryStreamConnection::Borrowed(conn),
            inner,
            finished: false,
            schema: None,
        })
    }

    pub(crate) fn start_owned_with_params(
        conn: Connection,
        sql: &str,
        params: impl Into<QueryParams>,
        opts: Option<&ArrowOptions>,
    ) -> Result<Self> {
        let inner = Self::start_query_with_params(conn.handle(), sql, params, opts)?;
        Ok(Self {
            conn: ArrowQueryStreamConnection::Owned(conn),
            inner,
            finished: false,
            schema: None,
        })
    }

    fn start_query(
        conn: bindings::chdb_connection,
        sql: &str,
        opts: Option<&ArrowOptions>,
    ) -> Result<*mut bindings::chdb_result> {
        // chdb_stream_query_arrow_n takes pointer + length for the query text,
        // so it does not have to be NUL-terminated. The C struct must outlive
        // the call, so it is materialized here rather than in a temporary
        // inside the argument list; a null options pointer asks for the
        // engine's default type mapping. 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 — ArrowQueryStream::cancel
        // (called from Drop) does both. `check_start`, below, probes the
        // handle for a start-up error without taking ownership of it.
        let c_opts = opts.map(|o| o.to_c());
        let opts_ptr = c_opts.as_ref().map_or(std::ptr::null(), |o| {
            o as *const bindings::chdb_arrow_options
        });

        let stream_ptr = unsafe {
            bindings::chdb_stream_query_arrow_n(
                conn,
                sql.as_ptr() as *const c_char,
                sql.len(),
                opts_ptr,
            )
        };

        Self::check_start(stream_ptr)
    }

    /// Wraps `chdb_stream_query_arrow_with_params_n`. A null options pointer
    /// asks for the engine's default type mapping. 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 — `ArrowQueryStream::cancel`
    /// (called from `Drop`) does both.
    /// 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,
        params: impl Into<QueryParams>,
        opts: Option<&ArrowOptions>,
    ) -> Result<*mut bindings::chdb_result> {
        let encoded = EncodedParams::encode(params)?;
        // Materialized into a named local so the pointer handed to C outlives the call.
        let c_opts = opts.map(|o| o.to_c());
        let opts_ptr = c_opts.as_ref().map_or(std::ptr::null(), |o| {
            o as *const bindings::chdb_arrow_options
        });

        // chdb_stream_query_arrow_with_params_n takes pointer + length for the query
        // and each bound value. A null options pointer selects the engine default
        // type mapping. It returns an owned streaming chdb_result handle (or null
        // on failure) that ArrowQueryStream::cancel (called from Drop) cancels and
        // frees.
        let stream_ptr = unsafe {
            bindings::chdb_stream_query_arrow_with_params_n(
                conn,
                sql.as_ptr() as *const c_char,
                sql.len(),
                opts_ptr,
                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 {
            ArrowQueryStreamConnection::Borrowed(conn) => conn.handle(),
            ArrowQueryStreamConnection::Owned(conn) => conn.handle(),
        }
    }

    /// Fetch the next Arrow record batch from the query stream.
    ///
    /// The schema, once fetched, remains available after this returns `None`.
    /// Older engines may not export a schema for a zero-row result.
    pub fn schema(&self) -> Option<arrow::datatypes::SchemaRef> {
        self.schema.clone()
    }

    /// Returns `Ok(None)` when the stream is exhausted, including empty result sets.
    pub fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
        if self.finished || self.inner.is_null() {
            return Ok(None);
        }

        let mut ffi_stream = FFI_ArrowArrayStream::empty();
        let out_ptr = (&mut ffi_stream as *mut FFI_ArrowArrayStream).cast();

        let state =
            unsafe { bindings::chdb_stream_fetch_arrow(self.conn_handle(), self.inner, out_ptr) };

        if state != bindings::chdb_state_CHDBSuccess {
            let err_msg = unsafe { bindings::chdb_result_error(self.inner) };
            let detail = if err_msg.is_null() {
                "chdb_stream_fetch_arrow failed".to_string()
            } else {
                unsafe { CStr::from_ptr(err_msg) }
                    .to_string_lossy()
                    .into_owned()
            };
            self.cancel();
            return Err(Error::QueryError(detail));
        }

        match is_eos_without_schema(&mut ffi_stream) {
            Ok(true) => {
                self.finished = true;
                return Ok(None);
            }
            Ok(false) => {}
            Err(err) => {
                self.cancel();
                return Err(err);
            }
        }

        let mut reader = match ArrowArrayStreamReader::try_new(ffi_stream) {
            Ok(reader) => reader,
            Err(e) => {
                self.cancel();
                return Err(Error::QueryError(e.to_string()));
            }
        };

        self.schema = Some(reader.schema());

        match reader.next() {
            Some(Ok(batch)) => Ok(Some(batch)),
            Some(Err(e)) => {
                self.cancel();
                Err(Error::QueryError(e.to_string()))
            }
            None => {
                self.finished = true;
                Ok(None)
            }
        }
    }

    /// Cancel the streaming query and release resources.
    pub fn cancel(&mut self) {
        if self.inner.is_null() {
            return;
        }

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

/// On older engines EOS may be a stream without a schema. A failed schema
/// callback alone is not proof of EOS: check get_next before deciding whether
/// to suppress the error. Both probe objects release themselves on drop.
fn is_eos_without_schema(ffi_stream: &mut FFI_ArrowArrayStream) -> Result<bool> {
    let Some(get_schema) = ffi_stream.get_schema else {
        return Err(Error::InvalidData(
            "Arrow stream has no get_schema callback".into(),
        ));
    };
    let mut schema = FFI_ArrowSchema::empty();
    let ret_code = unsafe { get_schema(ffi_stream, &mut schema) };
    if ret_code == 0 {
        return Ok(false);
    }

    let Some(get_next) = ffi_stream.get_next else {
        return Err(Error::InvalidData(
            "Arrow stream has no get_next callback".into(),
        ));
    };
    let mut array = FFI_ArrowArray::empty();
    let next_code = unsafe { get_next(ffi_stream, &mut array) };
    let detail = ffi_stream.get_last_error.and_then(|get_error| {
        let ptr = unsafe { get_error(ffi_stream) };
        (!ptr.is_null()).then(|| {
            unsafe { CStr::from_ptr(ptr) }
                .to_string_lossy()
                .into_owned()
        })
    });
    if next_code == 0 && array.release.is_none() && detail.is_none() {
        return Ok(true);
    }
    Err(Error::QueryError(detail.unwrap_or_else(|| {
        format!("Arrow stream schema failed ({ret_code}); next batch returned {next_code}")
    })))
}

impl Iterator for ArrowQueryStream<'_> {
    type Item = Result<RecordBatch>;

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

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session::SessionBuilder;
    use crate::test_utils::tempdir;

    unsafe extern "C" fn failing_schema(
        _: *mut FFI_ArrowArrayStream,
        _: *mut FFI_ArrowSchema,
    ) -> i32 {
        1
    }

    unsafe extern "C" fn empty_next(_: *mut FFI_ArrowArrayStream, _: *mut FFI_ArrowArray) -> i32 {
        0
    }

    unsafe extern "C" fn schema_error(_: *mut FFI_ArrowArrayStream) -> *const c_char {
        c"invalid schema".as_ptr()
    }

    #[test]
    fn schema_error_is_not_silently_treated_as_eof() {
        let mut stream = FFI_ArrowArrayStream::empty();
        stream.get_schema = Some(failing_schema);
        stream.get_next = Some(empty_next);
        stream.get_last_error = Some(schema_error);
        let err = is_eos_without_schema(&mut stream).unwrap_err();
        assert!(err.to_string().contains("invalid schema"));

        stream.get_last_error = None;
        assert!(is_eos_without_schema(&mut stream).unwrap());
    }

    #[test]
    fn test_arrow_query_stream_row_count_and_chunking() -> Result<()> {
        let mut conn = Connection::open_in_memory()?;
        let mut stream = conn.query_stream_arrow("SELECT number FROM numbers(100_000)")?;

        let mut batches = 0usize;
        let mut rows = 0usize;
        while let Some(batch) = stream.next_batch()? {
            batches += 1;
            rows += batch.num_rows();
        }

        assert_eq!(rows, 100_000);
        assert!(batches > 1, "expected multiple batches, got {batches}");
        Ok(())
    }

    #[test]
    fn test_execute_stream_arrow() -> Result<()> {
        use crate::execute_stream_arrow;

        let mut stream = execute_stream_arrow("SELECT number FROM numbers(10)")?;
        let mut rows = 0usize;
        while let Some(batch) = stream.next_batch()? {
            rows += batch.num_rows();
        }

        assert_eq!(rows, 10);
        Ok(())
    }

    #[test]
    fn test_session_execute_stream_arrow() -> 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_arrow("SELECT * FROM items")?;
        let mut rows = 0usize;
        while let Some(batch) = stream.next_batch()? {
            rows += batch.num_rows();
        }

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

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

        let batches: Vec<_> = stream.collect::<Result<Vec<_>>>()?;
        assert_eq!(batches.len(), 1);
        assert_eq!(batches[0].num_rows(), 5);
        Ok(())
    }

    #[test]
    fn test_arrow_query_stream_empty_filter_returns_none() -> 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_arrow("SELECT * FROM items WHERE id > 100")?;
        assert!(stream.next_batch()?.is_none());
        assert!(stream.next_batch()?.is_none());
        Ok(())
    }

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

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

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

    #[test]
    fn test_arrow_query_stream_with_params_empty_filter_returns_none() -> 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_arrow_with_params(
            "SELECT * FROM items WHERE id > {min_id:UInt64}",
            [("min_id", 100_u64)],
            None,
        )?;
        assert!(stream.next_batch()?.is_none());
        assert!(stream.next_batch()?.is_none());
        Ok(())
    }

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

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

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

    #[test]
    fn test_arrow_query_stream_early_drop() -> Result<()> {
        let mut conn = Connection::open_in_memory()?;
        let mut stream = conn.query_stream_arrow("SELECT number FROM numbers(1_000_000)")?;
        let first = stream.next_batch()?.expect("expected a batch");
        assert!(first.num_rows() > 0);
        drop(stream);
        Ok(())
    }
}