chdb-rust 1.4.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
//! Connection management for chDB.
//!
//! This module provides the [`Connection`] type for managing connections to chDB databases.

use std::ffi::{c_char, CString};

#[cfg(all(feature = "arrow", direct_arrow_insert))]
use crate::arrow_options::InsertOptions;
#[cfg(feature = "arrow")]
use crate::arrow_stream::{ArrowArray, ArrowSchema, ArrowStream};
use crate::error::{Error, Result};
use crate::format::OutputFormat;
use crate::query_result::QueryResult;
use crate::{bindings, CHDB_PROGRAM_NAME};

/// A connection to a chDB database.
///
/// A `Connection` represents an active connection to a chDB database instance.
/// Connections can be created for in-memory databases or persistent databases
/// stored on disk.
///
/// # Thread Safety
///
/// `Connection` implements `Send`, meaning it can be safely transferred between threads.
/// However, the underlying chDB library may have limitations on concurrent access.
/// It's recommended to use one connection per thread or implement proper synchronization.
///
/// # Examples
///
/// ```no_run
/// use chdb_rust::connection::Connection;
/// use chdb_rust::format::OutputFormat;
///
/// // Create an in-memory connection
/// let conn = Connection::open_in_memory()?;
///
/// // Execute a query
/// let result = conn.query("SELECT 1", OutputFormat::JSONEachRow)?;
/// println!("{}", result.data_utf8_lossy());
/// # Ok::<(), chdb_rust::error::Error>(())
/// ```
#[derive(Debug)]
pub struct Connection {
    // Pointer to chdb_connection (which is *mut chdb_connection_)
    inner: *mut bindings::chdb_connection,
}

// Safety: Connection is safe to send between threads
// The underlying chDB library is thread-safe for query execution
unsafe impl Send for Connection {}

impl Connection {
    /// Connect to chDB with the given command-line arguments.
    ///
    /// Use [crate::session::SessionBuilder] for a higher-level API that supports
    /// sessions and persistent storage.
    ///
    /// # Arguments
    ///
    /// * `args` - Array of command-line arguments (e.g., `["--path=/tmp/db"]`)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::connection::Connection;
    ///
    /// // Connect with custom arguments
    /// let conn = Connection::open(&["--path=/tmp/mydb"])?;
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::ConnectionFailed`] if the
    /// connection cannot be established.
    pub fn open(args: &[&str]) -> Result<Self> {
        let c_args: Vec<CString> = std::iter::once(CHDB_PROGRAM_NAME)
            .chain(args.iter().copied())
            .map(CString::new)
            .collect::<std::result::Result<_, _>>()?;

        let argv: Vec<*const c_char> = c_args.iter().map(|s| s.as_ptr()).collect();
        let conn_ptr =
            unsafe { bindings::chdb_connect(argv.len() as i32, argv.as_ptr() as *mut *mut c_char) };

        if conn_ptr.is_null() {
            return Err(Error::ConnectionFailed);
        }

        // Check if the connection itself is null
        let conn = unsafe { *conn_ptr };
        if conn.is_null() {
            return Err(Error::ConnectionFailed);
        }

        Ok(Self { inner: conn_ptr })
    }

    /// Connect to an in-memory database.
    ///
    /// Creates a connection to a temporary in-memory database. Data stored in this
    /// database will be lost when the connection is closed.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::connection::Connection;
    ///
    /// let conn = Connection::open_in_memory()?;
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::ConnectionFailed`] if the
    /// connection cannot be established.
    pub fn open_in_memory() -> Result<Self> {
        Self::open(&[])
    }

    /// Connect to a database at the given path.
    ///
    /// Creates a connection to a persistent database stored at the specified path.
    /// The directory will be created if it doesn't exist.
    ///
    /// # Arguments
    ///
    /// * `path` - The filesystem path where the database should be stored
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::connection::Connection;
    ///
    /// let conn = Connection::open_with_path("/tmp/mydb")?;
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::ConnectionFailed`] if the
    /// connection cannot be established.
    #[deprecated(note = "Use `SessionBuilder` instead")]
    pub fn open_with_path(path: &str) -> Result<Self> {
        let path_arg = format!("--path={path}");
        Self::open(&[&path_arg])
    }

    /// Execute a query and return the result.
    ///
    /// Executes a SQL query against the database and returns the result in the
    /// specified output format.
    ///
    /// # Arguments
    ///
    /// * `sql` - The SQL query string to execute
    /// * `format` - The desired output format for the result
    ///
    /// # Returns
    ///
    /// Returns a [`QueryResult`] containing the query output, or an [`Error`]
    /// if the query fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::connection::Connection;
    /// use chdb_rust::format::OutputFormat;
    ///
    /// let conn = Connection::open_in_memory()?;
    /// let result = conn.query("SELECT 1 + 1 AS sum", OutputFormat::JSONEachRow)?;
    /// println!("{}", result.data_utf8_lossy());
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The query syntax is invalid
    /// - The query references non-existent tables or columns
    /// - The query execution fails for any other reason
    pub fn query(&self, sql: &str, format: OutputFormat) -> Result<QueryResult> {
        let query_cstr = CString::new(sql)?;
        let format_cstr = CString::new(format.as_str())?;

        // chdb_query takes chdb_connection (which is *mut chdb_connection_)
        let conn = unsafe { *self.inner };
        let result_ptr =
            unsafe { bindings::chdb_query(conn, query_cstr.as_ptr(), format_cstr.as_ptr()) };

        if result_ptr.is_null() {
            return Err(Error::NoResult);
        }

        let result = QueryResult::new(result_ptr);
        result.check_error()
    }

    /// Register an Arrow C Data Interface stream for use with `ArrowStream('name')`.
    #[cfg(feature = "arrow")]
    ///
    /// Pass a raw `ArrowArrayStream*` (see [`ArrowStream`](crate::arrow_stream::ArrowStream)).
    /// Registered names are **not** ordinary tables; query them with the
    /// [`arrow_stream_table_sql`](crate::arrow_stream::arrow_stream_table_sql) helper, e.g.
    /// `SELECT * FROM ArrowStream('my_data')`.
    ///
    /// The stream pointer must stay valid until [`unregister_arrow_table`](Self::unregister_arrow_table)
    /// is called or the connection is dropped.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::arrow_stream::{arrow_stream_table_sql, ArrowStream};
    /// use chdb_rust::connection::Connection;
    /// use chdb_rust::format::OutputFormat;
    ///
    /// let conn = Connection::open_in_memory()?;
    /// // let stream_ptr: *mut arrow::ffi::FFI_ArrowArrayStream = ...;
    /// // let arrow_stream = unsafe { ArrowStream::from_raw(stream_ptr) };
    /// // conn.register_arrow_stream("my_data", &arrow_stream)?;
    /// // let sql = format!("SELECT * FROM {}", arrow_stream_table_sql("my_data"));
    /// // let _ = conn.query(&sql, OutputFormat::JSONEachRow)?;
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The table name contains invalid characters
    /// - The Arrow stream handle is invalid
    /// - Registration fails for any other reason
    pub fn register_arrow_stream(
        &self,
        table_name: &str,
        arrow_stream: &ArrowStream,
    ) -> Result<()> {
        let table_name_cstr = CString::new(table_name)?;
        let conn = unsafe { *self.inner };

        let state = unsafe {
            bindings::chdb_arrow_scan(conn, table_name_cstr.as_ptr(), arrow_stream.as_raw())
        };

        if state == bindings::chdb_state_CHDBSuccess {
            Ok(())
        } else {
            Err(Error::QueryError(format!(
                "Failed to register Arrow stream as table '{}'",
                table_name
            )))
        }
    }

    /// Register Arrow C Data Interface schema + array for use with `ArrowStream('name')`.
    #[cfg(feature = "arrow")]
    ///
    /// libchdb wraps the pair in a one-shot stream. Query via
    /// [`arrow_stream_table_sql`](crate::arrow_stream::arrow_stream_table_sql).
    ///
    /// # Arguments
    ///
    /// * `table_name` - The name to register for the Arrow stream table function
    /// * `arrow_schema` - The Arrow schema handle describing the array structure
    /// * `arrow_array` - The Arrow array handle containing the data
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an [`Error`] if registration fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::arrow_stream::{arrow_stream_table_sql, ArrowArray, ArrowSchema};
    /// use chdb_rust::connection::Connection;
    /// use chdb_rust::format::OutputFormat;
    ///
    /// let conn = Connection::open_in_memory()?;
    ///
    /// // Assuming you have Arrow C Data Interface schema and array handles
    /// // let arrow_schema = unsafe { ArrowSchema::from_raw(schema_ptr) };
    /// // let arrow_array = unsafe { ArrowArray::from_raw(array_ptr) };
    /// // conn.register_arrow_array("my_data", &arrow_schema, &arrow_array)?;
    ///
    /// // Query via the ArrowStream table function
    /// // let sql = format!("SELECT * FROM {}", arrow_stream_table_sql("my_data"));
    /// // let result = conn.query(&sql, OutputFormat::JSONEachRow)?;
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The table name contains invalid characters
    /// - The Arrow schema or array handles are invalid
    /// - Registration fails for any other reason
    pub fn register_arrow_array(
        &self,
        table_name: &str,
        arrow_schema: &ArrowSchema,
        arrow_array: &ArrowArray,
    ) -> Result<()> {
        let table_name_cstr = CString::new(table_name)?;
        let conn = unsafe { *self.inner };

        let state = unsafe {
            bindings::chdb_arrow_array_scan(
                conn,
                table_name_cstr.as_ptr(),
                arrow_schema.as_raw(),
                arrow_array.as_raw(),
            )
        };

        if state == bindings::chdb_state_CHDBSuccess {
            Ok(())
        } else {
            Err(Error::QueryError(format!(
                "Failed to register Arrow array as table '{}'",
                table_name
            )))
        }
    }

    /// Unregister an Arrow stream table function that was previously registered.
    #[cfg(feature = "arrow")]
    ///
    /// This function removes a previously registered Arrow stream table function,
    /// making it no longer available for queries.
    ///
    /// # Arguments
    ///
    /// * `table_name` - The name of the Arrow stream table function to unregister
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an [`Error`] if unregistration fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::connection::Connection;
    /// use chdb_rust::arrow_stream::ArrowStream;
    ///
    /// let conn = Connection::open_in_memory()?;
    ///
    /// // Register a table
    /// // let arrow_stream = ArrowStream::from_raw(stream_ptr);
    /// // conn.register_arrow_stream("my_data", &arrow_stream)?;
    ///
    /// // Use it...
    ///
    /// // Unregister when done
    /// // conn.unregister_arrow_table("my_data")?;
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The table name contains invalid characters
    /// - The table was not previously registered
    /// - Unregistration fails for any other reason
    pub fn unregister_arrow_table(&self, table_name: &str) -> Result<()> {
        let table_name_cstr = CString::new(table_name)?;
        let conn = unsafe { *self.inner };

        let state =
            unsafe { bindings::chdb_arrow_unregister_table(conn, table_name_cstr.as_ptr()) };

        if state == bindings::chdb_state_CHDBSuccess {
            Ok(())
        } else {
            Err(Error::QueryError(format!(
                "Failed to unregister Arrow table '{}'",
                table_name
            )))
        }
    }

    /// Insert rows from a registered Arrow schema+array directly into `dest_table`.
    ///
    /// Requires libchdb built with `chdb_insert_arrow_array` (see `direct_arrow_insert` cfg).
    #[cfg(all(feature = "arrow", direct_arrow_insert))]
    pub fn insert_arrow_array(
        &self,
        dest_table: &str,
        arrow_schema: &ArrowSchema,
        arrow_array: &ArrowArray,
        options: &InsertOptions,
    ) -> Result<()> {
        let dest_cstr = CString::new(dest_table)?;
        let (options_ptr, _settings) = build_insert_options_c(options)?;

        let conn = unsafe { *self.inner };
        let result_ptr = unsafe {
            bindings::chdb_insert_arrow_array(
                conn,
                dest_cstr.as_ptr(),
                arrow_schema.as_raw(),
                arrow_array.as_raw(),
                options_ptr,
            )
        };

        check_insert_result(result_ptr)
    }

    /// Insert rows from a registered Arrow stream directly into `dest_table`.
    ///
    /// Requires libchdb built with `chdb_insert_arrow_stream` (see `direct_arrow_insert` cfg).
    #[cfg(all(feature = "arrow", direct_arrow_insert))]
    pub fn insert_arrow_stream(
        &self,
        dest_table: &str,
        arrow_stream: &ArrowStream,
        options: &InsertOptions,
    ) -> Result<()> {
        let dest_cstr = CString::new(dest_table)?;
        let (options_ptr, _settings) = build_insert_options_c(options)?;

        let conn = unsafe { *self.inner };
        let result_ptr = unsafe {
            bindings::chdb_insert_arrow_stream(
                conn,
                dest_cstr.as_ptr(),
                arrow_stream.as_raw(),
                options_ptr,
            )
        };

        check_insert_result(result_ptr)
    }
}

#[cfg(all(feature = "arrow", direct_arrow_insert))]
fn build_insert_options_c(
    options: &InsertOptions,
) -> Result<(*const bindings::chdb_arrow_insert_options, Option<CString>)> {
    let settings_cstr = options.settings_clause().map(CString::new).transpose()?;
    let c_options = settings_cstr
        .as_ref()
        .map(|settings| bindings::chdb_arrow_insert_options {
            settings: settings.as_ptr(),
        });
    let options_ptr = c_options
        .as_ref()
        .map(|opts| opts as *const bindings::chdb_arrow_insert_options)
        .unwrap_or(std::ptr::null());
    Ok((options_ptr, settings_cstr))
}

#[cfg(all(feature = "arrow", direct_arrow_insert))]
fn check_insert_result(result_ptr: *mut bindings::chdb_result) -> Result<()> {
    if result_ptr.is_null() {
        return Err(Error::NoResult);
    }

    let result = QueryResult::new(result_ptr);
    result.check_error().map(|_| ())
}

impl Drop for Connection {
    fn drop(&mut self) {
        if !self.inner.is_null() {
            unsafe { bindings::chdb_close_conn(self.inner) };
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{error::Result, test_utils::tempdir};

    #[test]
    fn test_connection_open_with_explicit_data_path() -> Result<()> {
        let tmp = tempdir();
        let path_arg = format!(
            "--path={}",
            tmp.path().to_str().expect("temp path is not valid UTF-8")
        );
        Connection::open(&[&path_arg])?;

        assert!(
            tmp.path().read_dir()?.next().is_some(),
            "expected chDB to create files in the data dir"
        );

        Ok(())
    }
}