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
//! # chdb-rust
//!
//! Rust FFI bindings for [chDB](https://github.com/chdb-io/chdb), an embedded ClickHouse database.
//!
//! ## Overview
//!
//! This crate provides a safe Rust interface to chDB, allowing you to execute ClickHouse SQL queries
//! either statelessly (in-memory) or with persistent storage using sessions.
//!
//! ## Quick Start
//!
//! ```no_run
//! use chdb_rust::execute;
//! use chdb_rust::arg::Arg;
//! use chdb_rust::format::OutputFormat;
//!
//! // Execute a simple query
//! let result = execute("SELECT 1 + 1 AS sum", None)?;
//! println!("Result: {}", result.data_utf8_lossy());
//! # Ok::<(), chdb_rust::error::Error>(())
//! ```
//!
//! ## Features
//!
//! - **Stateless queries**: Execute one-off queries without persistent storage
//! - **Stateful sessions**: Create databases and tables with persistent storage
//! - **Parameterized queries**: Bind ClickHouse `{name:Type}` placeholders with [`execute_with_params`] and [`QueryParam`], across buffered, streaming, Arrow-streaming and insert statements. Values are bound in the chDB library and never spliced into the SQL text
//! - **Multiple output formats**: JSON, CSV, TabSeparated, and more
//! - **Query result streaming**: Read large result sets in chunks with constant memory
//! - **Streaming INSERT** ([`insert_stream`]): push rows in chunks in any input format, with engine backpressure; the stream also implements [`std::io::Write`]
//! - **Arrow bulk insert** (feature `arrow`, on by default): [`insert_record_batch`] via `ArrowStream('name')`. Use [`chdb_rust::arrow`](arrow) types so your Arrow version matches the crate.
//! - **Arrow batch streaming** (with the `arrow` feature): Stream query results as `RecordBatch` values via the Arrow C Data Interface
//! - **One-shot Arrow export** (with the `arrow` feature): take a whole result as one Arrow stream via [`connection::Connection::query_arrow`], with [`arrow_options::ArrowOptions`] controlling the type mapping on both the one-shot and streaming paths
//! - **Thread-safe**: Connections and results can be safely sent between threads
//! - **Version accessors** ([`version`]): which chdb-core release is linked, where it came from, and which ClickHouse it carries
//! - **Backup, restore and statement analysis** ([`admin`]): the chdb-core management ABI, on any engine that exports it
//! - **Durable objects** (feature `durable`, [`durable`]): a database whose authoritative state is a checkpoint plus a statement WAL in storage you own
//! - **Runtime control** ([`runtime`]): decline chDB's process-wide signal handlers, and shut the engine down cleanly so no engine thread outlives your teardown
//!
//! ## Examples
//!
//! See the [`examples`](https://github.com/chdb-io/chdb-rust/tree/main/examples) directory for more detailed examples.
//!
//! ## Safety
//!
//! This crate uses `unsafe` code to interface with the C library, but provides a safe Rust API.
//! All public functions are safe to call, and the crate ensures proper resource cleanup.
pub use arrow;
pub use ;
pub use ;
pub use ;
pub use arrow_stream_table_sql;
// The `durable` feature needs the chdb-core management ABI, and a library that
// does not export it cannot serve a durable object at all. Saying so at compile
// time beats a link error naming three symbols.
compile_error!;
pub use ;
pub
pub use ;
pub use QueryResult;
use crate;
use crateConnection;
use crateResult;
use crateOutputFormat;
use crateQueryStream;
pub const CHDB_PROGRAM_NAME: &str = "clickhouse";
/// Execute a one-off query using an in-memory connection.
///
/// This function creates a temporary in-memory database connection, executes the query,
/// and returns the result. It's suitable for queries that don't require persistent storage.
///
/// # Arguments
///
/// * `query` - The SQL query string to execute
/// * `query_args` - Optional array of query arguments (e.g., output format)
///
/// # Returns
///
/// Returns a [`QueryResult`] containing the query output, or an [`Error`](error::Error) if
/// the query fails.
///
/// # Examples
///
/// ```no_run
/// use chdb_rust::execute;
/// use chdb_rust::arg::Arg;
/// use chdb_rust::format::OutputFormat;
///
/// // Simple query with default format
/// let result = execute("SELECT 1 + 1 AS sum", None)?;
/// println!("{}", result.data_utf8_lossy());
///
/// // Query with JSON output format
/// let result = execute(
/// "SELECT 'Hello' AS greeting, 42 AS answer",
/// Some(&[Arg::OutputFormat(OutputFormat::JSONEachRow)])
/// )?;
/// println!("{}", result.data_utf8_lossy());
/// # Ok::<(), chdb_rust::error::Error>(())
/// ```
///
/// # Errors
///
/// This function will return an error if:
/// - The query syntax is invalid
/// - The connection cannot be established
/// - The query execution fails
/// - A connection is already open on a data path, since the in-memory
/// connection this opens would be a second one. See
/// [`Error::PathConflict`](error::Error::PathConflict).
/// The data path the embedded engine is bound to, or `None` when no connection
/// is open. `:memory:` for an in-memory engine, a directory otherwise.
/// How many open connections are holding the embedded engine. Zero means the
/// next connection may bind any path.
/// Execute a one-off query with ClickHouse `{name:Type}` parameter binding.
///
/// Counterpart to [`execute`]. Parameter values are bound in the chDB library
/// and never interpolated into the SQL text. Names in `params` need not match placeholder
/// order. An empty `params` list is a plain query: placeholders then fail with a
/// substitution error.
///
/// # Examples
///
/// ```no_run
/// use chdb_rust::arg::Arg;
/// use chdb_rust::execute_with_params;
/// use chdb_rust::format::OutputFormat;
///
/// let result = execute_with_params(
/// "SELECT {x:UInt64} AS v",
/// Some(&[Arg::OutputFormat(OutputFormat::CSV)]),
/// [("x", 7_u64)],
/// )?;
/// # Ok::<(), chdb_rust::error::Error>(())
/// ```
///
/// # Errors
///
/// This function will return an error if:
/// - The query syntax is invalid
/// - A `{name:Type}` placeholder has no matching param
/// - A value cannot be parsed as the type declared in the placeholder
/// - The connection cannot be established
/// - The query execution fails
/// - A connection is already open on a data path, since the in-memory
/// connection this opens would be a second one. See
/// [`Error::PathConflict`](error::Error::PathConflict).
/// Execute a one-off streaming query using an in-memory connection.
///
/// This function creates a temporary in-memory database connection, starts a
/// streaming query, and returns a [`QueryStream`] that owns the connection.
/// The connection is kept alive until the stream is dropped.
///
/// Primarily useful for reading external data: CSV files, S3, Parquet, etc.
///
/// # Arguments
///
/// * `query` - The SQL query string to execute
/// * `query_args` - Optional array of query arguments (e.g., output format)
///
/// # Returns
///
/// Returns a [`QueryStream`] that owns the temporary connection, or an
/// [`Error`](error::Error) if the query cannot be started.
///
/// # Examples
///
/// ```no_run
/// use chdb_rust::execute_stream;
/// use chdb_rust::arg::Arg;
/// use chdb_rust::format::OutputFormat;
///
/// let mut stream = execute_stream(
/// "SELECT number FROM numbers(100_000)",
/// Some(&[Arg::OutputFormat(OutputFormat::JSONEachRow)]),
/// )?;
///
/// while let Some(chunk) = stream.next_chunk()? {
/// print!("{}", chunk.data_utf8_lossy());
/// }
/// # Ok::<(), chdb_rust::error::Error>(())
/// ```
///
/// # Errors
///
/// This function will return an error if:
/// - The query syntax is invalid
/// - The connection cannot be established
/// - The query execution fails
/// Execute a one-off query with ClickHouse `{name:Type}` parameter binding and stream text chunks.
///
/// Counterpart to [`execute_stream`]. Syntax errors fail when the stream is
/// created. A missing placeholder binding is reported on the first
/// [`QueryStream::next_chunk`], not at start.
///
/// # Examples
///
/// ```no_run
/// use chdb_rust::arg::Arg;
/// use chdb_rust::execute_stream_with_params;
/// use chdb_rust::format::OutputFormat;
///
/// let mut stream = execute_stream_with_params(
/// "SELECT {x:UInt64} AS v",
/// Some(&[Arg::OutputFormat(OutputFormat::CSV)]),
/// [("x", 11_u64)],
/// )?;
/// while let Some(chunk) = stream.next_chunk()? {
/// print!("{}", chunk.data_utf8_lossy());
/// }
/// # Ok::<(), chdb_rust::error::Error>(())
/// ```
///
/// # Errors
///
/// This function will return an error if:
/// - The query syntax is invalid
/// - The connection cannot be established
/// - The query cannot be started
/// - A connection is already open on a data path. See
/// [`Error::PathConflict`](error::Error::PathConflict).
/// Execute a one-off Arrow streaming query using an in-memory connection.
///
/// Returns an [`ArrowQueryStream`] that owns the temporary connection and yields
/// [`arrow::record_batch::RecordBatch`] values via the Arrow C Data Interface.
///
/// Available when the crate is built with the `arrow` feature.
///
/// # Examples
///
/// ```no_run
/// use chdb_rust::execute_stream_arrow;
///
/// let mut stream = execute_stream_arrow("SELECT number FROM numbers(100_000)")?;
/// while let Some(batch) = stream.next_batch()? {
/// println!("rows: {}", batch.num_rows());
/// }
/// # Ok::<(), chdb_rust::error::Error>(())
/// ```
/// Execute a one-off query with ClickHouse `{name:Type}` parameter binding and stream Arrow batches.
///
/// Counterpart to [`execute_stream_arrow`]. Syntax errors fail when the stream is
/// created. A missing placeholder binding is reported on the first
/// [`ArrowQueryStream::next_batch`], not at start.
///
/// # Examples
///
/// ```no_run
/// use chdb_rust::execute_stream_arrow_with_params;
///
/// let mut stream =
/// execute_stream_arrow_with_params("SELECT {x:UInt64} AS v", [("x", 11_u64)])?;
/// while let Some(batch) = stream.next_batch()? {
/// println!("rows: {}", batch.num_rows());
/// }
/// # Ok::<(), chdb_rust::error::Error>(())
/// ```
///
/// # Errors
///
/// This function will return an error if:
/// - The query syntax is invalid
/// - The connection cannot be established
/// - The query cannot be started
/// - A connection is already open on a data path. See
/// [`Error::PathConflict`](error::Error::PathConflict).