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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
//! Session management for persistent chDB databases.
//!
//! This module provides the [`Session`] and [`SessionBuilder`] types for managing
//! persistent database connections with automatic cleanup.

use std::path::{Path, PathBuf};
use std::{fs, io};

#[cfg(feature = "arrow")]
use arrow::array::{RecordBatch, RecordBatchReader};
#[cfg(feature = "arrow")]
use arrow::datatypes::SchemaRef;

use crate::arg::{extract_output_format, Arg};
#[cfg(feature = "arrow")]
use crate::arrow_insert::{
    insert_record_batch, insert_record_batch_direct, insert_record_batch_reader,
    insert_record_batches,
};
#[cfg(feature = "arrow")]
use crate::arrow_options::{ArrowOptions, InsertOptions};
#[cfg(feature = "arrow")]
use crate::arrow_query_stream::ArrowQueryStream;
use crate::connection::Connection;
use crate::error::{Error, Result};
use crate::format::{InputFormat, OutputFormat};
use crate::insert_stream::InsertStream;
use crate::query_param::QueryParams;
use crate::query_result::QueryResult;
use crate::query_stream::QueryStream;

/// Builder for creating [`Session`] instances.
///
/// `SessionBuilder` provides a fluent API for configuring and creating sessions.
/// Use [`new`](Self::new) to create a new builder, configure it with the desired
/// options, and call [`build`](Self::build) to create the session.
///
/// # Examples
///
/// ```no_run
/// use chdb_rust::session::SessionBuilder;
///
/// // Create a session with default settings
/// let session = SessionBuilder::new()
///     .with_data_path("/tmp/mydb")
///     .with_auto_cleanup(true)
///     .build()?;
/// # Ok::<(), chdb_rust::error::Error>(())
/// ```
pub struct SessionBuilder<'a> {
    data_path: PathBuf,
    default_format: OutputFormat,
    arguments: Vec<Arg<'a>>,
    auto_cleanup: bool,
}

/// A session representing a persistent connection to a chDB database.
///
/// A `Session` manages a connection to a persistent database stored on disk.
/// Unlike stateless queries, sessions allow you to create tables, insert data,
/// and maintain state across multiple queries.
///
/// # Thread Safety
///
/// `Session` contains a [`Connection`] which implements
/// `Send`, so sessions can be safely transferred between threads. However, concurrent
/// access to the same session should be synchronized.
///
/// # Examples
///
/// ```no_run
/// use chdb_rust::session::SessionBuilder;
/// use chdb_rust::arg::Arg;
/// use chdb_rust::format::OutputFormat;
///
/// let session = SessionBuilder::new()
///     .with_data_path("/tmp/mydb")
///     .with_auto_cleanup(true)
///     .build()?;
///
/// // Create a table
/// session.execute(
///     "CREATE TABLE users (id UInt64, name String) ENGINE = MergeTree() ORDER BY id",
///     None
/// )?;
///
/// // Insert data
/// session.execute("INSERT INTO users VALUES (1, 'Alice')", None)?;
///
/// // Query data
/// let result = session.execute(
///     "SELECT * FROM users",
///     Some(&[Arg::OutputFormat(OutputFormat::JSONEachRow)])
/// )?;
/// println!("{}", result.data_utf8_lossy());
/// # Ok::<(), chdb_rust::error::Error>(())
/// ```
#[derive(Debug)]
pub struct Session {
    /// An `Option` so that [`Drop`] can release the connection before removing
    /// the directory it was using.
    conn: Option<Connection>,
    data_path: PathBuf,
    default_format: OutputFormat,
}

impl<'a> SessionBuilder<'a> {
    /// Create a new `SessionBuilder` with default settings.
    ///
    /// The default settings are:
    /// - Data path: current working directory. The `build` method will create a `chdb`
    ///   subdirectory if the path is not set.
    /// - Output format: `TabSeparated`
    /// - Auto cleanup: `false`
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::session::SessionBuilder;
    ///
    /// let builder = SessionBuilder::new();
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    pub fn new() -> Self {
        Self {
            data_path: PathBuf::new(),
            default_format: OutputFormat::TabSeparated,
            arguments: Vec::new(),
            auto_cleanup: false,
        }
    }

    /// Set the data path for the session.
    ///
    /// This specifies the filesystem path where the database will be stored.
    /// The directory will be created if it doesn't exist.
    ///
    /// # Arguments
    ///
    /// * `path` - The path where the database should be stored
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::session::SessionBuilder;
    ///
    /// let builder = SessionBuilder::new()
    ///     .with_data_path("/tmp/mydb");
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    pub fn with_data_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.data_path = path.into();
        self
    }

    /// Add a query argument to the session builder.
    ///
    /// If `OutputFormat` argument is provided it will be used
    /// as the default output format for queries executed on this session.
    ///
    /// Moreover, `OutputFormat` is consumed by the session layer and is not
    /// forwarded as a command-line argument to the connection.
    ///
    /// # Arguments
    ///
    /// * `arg` - The argument to add
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::session::SessionBuilder;
    /// use chdb_rust::arg::Arg;
    /// use chdb_rust::format::OutputFormat;
    /// use std::borrow::Cow;
    ///
    /// let builder = SessionBuilder::new()
    ///     .with_arg(Arg::OutputFormat(OutputFormat::JSONEachRow))
    ///     .with_arg(Arg::ConfigFilePath(Cow::from("chdb_ssl.xml")))
    ///     .with_arg(Arg::Custom(Cow::from("progress"), Some(Cow::from("err"))));
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    /// Custom arguments can be used to specify any additional command-line arguments
    /// that can be found by running `clickhouse-client --help` in
    /// the terminal.
    pub fn with_arg(mut self, arg: Arg<'a>) -> Self {
        if let Some(fmt) = arg.as_output_format() {
            self.default_format = fmt;
        } else {
            self.arguments.push(arg);
        }
        self
    }

    /// Enable or disable automatic cleanup of the data directory.
    ///
    /// If set to `true`, the session will automatically delete the data directory
    /// when it is dropped. This is useful for temporary databases.
    ///
    /// # Arguments
    ///
    /// * `value` - Whether to enable automatic cleanup
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::session::SessionBuilder;
    ///
    /// // Session will clean up data directory on drop
    /// let session = SessionBuilder::new()
    ///     .with_data_path("/tmp/tempdb")
    ///     .with_auto_cleanup(true)
    ///     .build()?;
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    pub fn with_auto_cleanup(mut self, value: bool) -> Self {
        self.auto_cleanup = value;
        self
    }

    /// Build the session with the configured settings.
    ///
    /// This creates the data directory if it doesn't exist and establishes
    /// a connection to the database. All configured arguments are passed to
    /// the connection.
    ///
    /// # Returns
    ///
    /// Returns a [`Session`] if successful, or an [`Error`] if
    /// the session cannot be created.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The data path cannot be created
    /// - The data path has insufficient permissions
    /// - The connection cannot be established
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::session::SessionBuilder;
    ///
    /// let session = SessionBuilder::new()
    ///     .with_data_path("/tmp/mydb")
    ///     .build()?;
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    pub fn build(mut self) -> Result<Session> {
        if self.data_path.as_os_str().is_empty() {
            let mut default_path = std::env::current_dir()?;
            default_path.push("chdb");
            self.data_path = default_path;
        }

        let dir_already_existed = self.data_path.exists();
        fs::create_dir_all(&self.data_path)?;
        let probe_path = self.data_path.join(".write_probe");
        if let Err(e) = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&probe_path)
        {
            if !dir_already_existed {
                fs::remove_dir(&self.data_path).ok();
            }
            return Err(match e.kind() {
                io::ErrorKind::PermissionDenied => Error::InsufficientPermissions,
                _ => Error::Io(e),
            });
        }
        fs::remove_file(&probe_path).ok(); // best-effort cleanup of write probe

        // The engine compares path strings verbatim, so spellings converge
        // before it sees them: "db", "./db" and "db/" reach it as one string
        // and share an engine. Only the argument is canonical; data_path stays
        // as given, so cleanup removes what the caller named rather than what a
        // symlink pointed at.
        let canonical = self.data_path.canonicalize()?;
        let canonical = canonical.to_str().ok_or(Error::PathError)?;
        let path_arg = format!("--path={canonical}");
        let owned: Vec<String> = self.arguments.iter().map(|a| a.to_string()).collect();
        let mut args: Vec<&str> = Vec::with_capacity(1 + owned.len());
        args.push(&path_arg);
        args.extend(owned.iter().map(String::as_str));

        let mut conn = Connection::open(&args)?;
        if self.auto_cleanup {
            conn.remove_dir_on_last(self.data_path.clone());
        }

        Ok(Session {
            conn: Some(conn),
            data_path: self.data_path,
            default_format: self.default_format,
        })
    }
}

impl Default for SessionBuilder<'_> {
    fn default() -> Self {
        Self::new()
    }
}

impl Session {
    /// Execute a query on this session.
    ///
    /// This executes a SQL query against the database associated with this session.
    /// The query can create tables, insert data, or query existing data.
    ///
    /// # Arguments
    ///
    /// * `query` - The SQL query string to execute
    /// * `query_args` - Optional array of query arguments (e.g., output format).
    ///
    /// Only `OutputFormat` is currently supported and will override the
    /// session's default output format for this query.
    ///
    /// # Returns
    ///
    /// Returns a [`QueryResult`] containing the query output,
    /// or an [`Error`] if the query fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::session::SessionBuilder;
    /// use chdb_rust::arg::Arg;
    /// use chdb_rust::format::OutputFormat;
    ///
    /// let session = SessionBuilder::new()
    ///     .with_data_path("/tmp/mydb")
    ///     .with_auto_cleanup(true)
    ///     .build()?;
    ///
    /// // Create a table
    /// session.execute(
    ///     "CREATE TABLE test (id UInt64) ENGINE = MergeTree() ORDER BY id",
    ///     None
    /// )?;
    ///
    /// // Query with JSON output
    /// let result = session.execute(
    ///     "SELECT * FROM test",
    ///     Some(&[Arg::OutputFormat(OutputFormat::JSONEachRow)])
    /// )?;
    /// # 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 execute(&self, query: &str, query_args: Option<&[Arg]>) -> Result<QueryResult> {
        let fmt = extract_output_format(query_args, self.default_format);
        self.connection().query(query, fmt)
    }

    /// Execute a query and return a streaming result.
    ///
    /// Like [`execute`](Self::execute), but returns a [`QueryStream`] that yields
    /// result data in chunks instead of materializing the full output at once.
    ///
    /// # Arguments
    ///
    /// * `query` - The SQL query string to execute
    /// * `query_args` - Optional array of query arguments (e.g., output format).
    ///
    /// Only `OutputFormat` is currently supported and will override the
    /// session's default output format for this query.
    ///
    /// # Returns
    ///
    /// Returns a [`QueryStream`] tied to this session's connection, or an [`Error`]
    /// if the query cannot be started.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::session::SessionBuilder;
    /// use chdb_rust::arg::Arg;
    /// use chdb_rust::format::OutputFormat;
    ///
    /// let mut session = SessionBuilder::new()
    ///     .with_data_path("/tmp/mydb")
    ///     .with_auto_cleanup(true)
    ///     .build()?;
    ///
    /// let mut stream = session.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
    ///
    /// 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 execute_stream<'a>(
        &'a mut self,
        query: &str,
        query_args: Option<&[Arg]>,
    ) -> Result<QueryStream<'a>> {
        let fmt = extract_output_format(query_args, self.default_format);
        self.connection_mut().query_stream(query, fmt)
    }

    /// Execute a query with ClickHouse `{name:Type}` parameter binding and stream the result in chunks.
    ///
    /// Like [`Self::execute_stream`], but SQL placeholders are bound from `params`
    /// before streaming begins. The session is exclusively borrowed for the
    /// stream's lifetime. Output format may be supplied via `query_args`; other
    /// [`Arg`] variants are ignored here, matching [`Self::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::format::OutputFormat;
    /// use chdb_rust::session::SessionBuilder;
    ///
    /// let mut session = SessionBuilder::new()
    ///     .with_data_path("/tmp/mydb")
    ///     .with_auto_cleanup(true)
    ///     .build()?;
    ///
    /// let mut stream = session.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
    ///
    /// Returns an error if:
    /// - The query syntax is invalid
    /// - The query cannot be started
    pub fn execute_stream_with_params<'a>(
        &'a mut self,
        query: &str,
        query_args: Option<&[Arg]>,
        params: impl Into<QueryParams>,
    ) -> Result<QueryStream<'a>> {
        let fmt = extract_output_format(query_args, self.default_format);
        self.connection_mut()
            .query_stream_with_params(query, fmt, params)
    }

    /// Open a streaming INSERT on this session's connection.
    ///
    /// Session-level counterpart of [`Connection::insert_stream`](crate::connection::Connection::insert_stream).
    /// The session is exclusively borrowed until the stream is finished, cancelled
    /// or dropped.
    ///
    /// # Errors
    ///
    /// Returns an error if the INSERT statement is invalid when the stream is opened.
    pub fn insert_stream<'a>(
        &'a mut self,
        sql: &str,
        format: InputFormat,
    ) -> Result<InsertStream<'a>> {
        self.connection_mut().insert_stream(sql, format)
    }

    /// Open a streaming INSERT whose statement carries `{name:Type}` placeholders.
    ///
    /// Session-level counterpart of
    /// [`Connection::insert_stream_with_params`](crate::connection::Connection::insert_stream_with_params).
    pub fn insert_stream_with_params<'a>(
        &'a mut self,
        sql: &str,
        format: InputFormat,
        params: impl Into<QueryParams>,
    ) -> Result<InsertStream<'a>> {
        self.connection_mut()
            .insert_stream_with_params(sql, format, params)
    }

    /// Execute a query with ClickHouse `{name:Type}` parameter binding.
    ///
    /// Like [`Self::execute`], but SQL placeholders are bound from `params`
    /// in the chDB library and never interpolated into the SQL text. Output format may
    /// be supplied via `query_args`; other [`Arg`] variants are ignored here,
    /// matching [`Self::execute`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::arg::Arg;
    /// use chdb_rust::format::OutputFormat;
    /// use chdb_rust::session::SessionBuilder;
    ///
    /// let session = SessionBuilder::new()
    ///     .with_data_path("/tmp/mydb")
    ///     .with_auto_cleanup(true)
    ///     .build()?;
    ///
    /// let result = session.execute_with_params(
    ///     "SELECT {x:UInt64} AS v",
    ///     Some(&[Arg::OutputFormat(OutputFormat::CSV)]),
    ///     [("x", 7_u64)],
    /// )?;
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns 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 query execution fails for any other reason
    pub fn execute_with_params(
        &self,
        query: &str,
        query_args: Option<&[Arg]>,
        params: impl Into<QueryParams>,
    ) -> Result<QueryResult> {
        let fmt = extract_output_format(query_args, self.default_format);
        self.connection().query_with_params(query, fmt, params)
    }

    /// Access the session's [`Connection`] for Arrow registration and low-level queries.
    pub fn connection(&self) -> &Connection {
        self.conn
            .as_ref()
            .expect("a session holds its connection until it is dropped")
    }

    /// Access the session's [`Connection`] mutably for APIs that exist only on
    /// [`Connection`] today (for example [`Connection::query_stream_arrow_with_opts`](crate::connection::Connection::query_stream_arrow_with_opts)).
    ///
    /// Streaming query and INSERT methods on [`Session`] borrow the connection
    /// exclusively while a stream is open because chDB accepts no other
    /// statement on that connection meanwhile.
    pub fn connection_mut(&mut self) -> &mut Connection {
        self.conn
            .as_mut()
            .expect("a session holds its connection until it is dropped")
    }

    /// The data path this session is on, as it was given.
    pub fn path(&self) -> &Path {
        &self.data_path
    }

    /// Closes this session and removes its data directory, whether or not
    /// [`SessionBuilder::with_auto_cleanup`] was set, and only once this is the
    /// last handle on the path.
    ///
    /// Removal is best effort, as it is on drop: it happens while the engine
    /// record is locked, so there is no error to hand back.
    pub fn cleanup(mut self) {
        let dir = self.data_path.clone();
        if let Some(conn) = self.conn.as_mut() {
            conn.remove_dir_on_last(dir);
        }
        drop(self.conn.take());
    }

    /// See [`insert_record_batch`].
    #[cfg(feature = "arrow")]
    pub fn insert_record_batch(
        &self,
        dest_table: &str,
        stream_name: &str,
        batch: RecordBatch,
        options: InsertOptions,
    ) -> Result<()> {
        insert_record_batch(self.connection(), dest_table, stream_name, batch, options)
    }

    /// See [`insert_record_batch_direct`].
    #[cfg(feature = "arrow")]
    pub fn insert_record_batch_direct(
        &self,
        dest_table: &str,
        batch: RecordBatch,
        options: InsertOptions,
    ) -> Result<()> {
        insert_record_batch_direct(self.connection(), dest_table, batch, options)
    }

    /// See [`insert_record_batches`].
    #[cfg(feature = "arrow")]
    pub fn insert_record_batches(
        &self,
        dest_table: &str,
        stream_name: &str,
        schema: SchemaRef,
        batches: Vec<RecordBatch>,
        options: InsertOptions,
    ) -> Result<()> {
        insert_record_batches(
            self.connection(),
            dest_table,
            stream_name,
            schema,
            batches,
            options,
        )
    }

    /// See [`insert_record_batch_reader`].
    #[cfg(feature = "arrow")]
    pub fn insert_record_batch_reader(
        &self,
        dest_table: &str,
        stream_name: &str,
        reader: Box<dyn RecordBatchReader + Send>,
        options: InsertOptions,
    ) -> Result<()> {
        insert_record_batch_reader(self.connection(), dest_table, stream_name, reader, options)
    }

    /// Execute a query and stream the result as Arrow record batches.
    ///
    /// Session-level counterpart of
    /// [`Connection::query_stream_arrow`](crate::connection::Connection::query_stream_arrow).
    ///
    /// Available when the crate is built with the `arrow` feature.
    #[cfg(feature = "arrow")]
    pub fn execute_stream_arrow<'a>(
        &'a mut self,
        query: &str,
    ) -> Result<crate::arrow_query_stream::ArrowQueryStream<'a>> {
        self.connection_mut().query_stream_arrow(query)
    }

    /// Execute a query with ClickHouse `{name:Type}` parameter binding and stream Arrow record batches.
    ///
    /// Session-level counterpart of
    /// [`Connection::query_stream_arrow_with_params`](crate::connection::Connection::query_stream_arrow_with_params).
    /// The session is exclusively borrowed for the stream's lifetime.
    ///
    /// Available when the crate is built with the `arrow` feature.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chdb_rust::session::SessionBuilder;
    ///
    /// let mut session = SessionBuilder::new()
    ///     .with_data_path("/tmp/mydb")
    ///     .with_auto_cleanup(true)
    ///     .build()?;
    ///
    /// let mut stream = session.execute_stream_arrow_with_params(
    ///     "SELECT {x:UInt64} AS v",
    ///     [("x", 11_u64)],
    ///     None,
    /// )?;
    /// while let Some(batch) = stream.next_batch()? {
    ///     println!("rows: {}", batch.num_rows());
    /// }
    /// # Ok::<(), chdb_rust::error::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The query syntax is invalid
    /// - The query cannot be started
    #[cfg(feature = "arrow")]
    pub fn execute_stream_arrow_with_params<'a>(
        &'a mut self,
        query: &str,
        params: impl Into<QueryParams>,
        opts: Option<&ArrowOptions>,
    ) -> Result<ArrowQueryStream<'a>> {
        self.connection_mut()
            .query_stream_arrow_with_params(query, params, opts)
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        // Releasing the connection is the whole teardown. Whether this was the
        // last handle, and so whether the directory goes, is decided while the
        // engine record is locked; deciding it here would race both a fresh
        // connection on the same path and another session releasing at the same
        // moment.
        drop(self.conn.take());
    }
}

#[cfg(test)]
mod test {
    use crate::test_utils::tempdir;

    use super::*;

    #[test]
    fn test_session_builder_no_args_still_builds() -> Result<()> {
        let tmp = tempdir();
        SessionBuilder::new().with_data_path(tmp.path()).build()?;
        Ok(())
    }

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

        let resp = session.execute("SELECT 'foo' AS name, 1 AS count", None)?;

        assert_eq!(resp.data_utf8_lossy(), "foo\t1\n");

        Ok(())
    }

    #[test]
    fn test_query_output_format_overrides_session_builder_output_format() -> Result<()> {
        let tmp = tempdir();
        let session = SessionBuilder::new()
            .with_data_path(tmp.path())
            .with_arg(Arg::OutputFormat(OutputFormat::Parquet))
            .build()?;

        let resp = session.execute(
            "SELECT 1 AS count",
            Some(&[Arg::OutputFormat(OutputFormat::JSONEachRow)]),
        )?;

        assert_eq!(resp.data_utf8_lossy(), "{\"count\":1}\n");

        Ok(())
    }
}