chdb_rust/session.rs
1//! Session management for persistent chDB databases.
2//!
3//! This module provides the [`Session`] and [`SessionBuilder`] types for managing
4//! persistent database connections with automatic cleanup.
5
6use std::path::{Path, PathBuf};
7use std::{fs, io};
8
9#[cfg(feature = "arrow")]
10use arrow::array::{RecordBatch, RecordBatchReader};
11#[cfg(feature = "arrow")]
12use arrow::datatypes::SchemaRef;
13
14use crate::arg::{extract_output_format, Arg};
15#[cfg(feature = "arrow")]
16use crate::arrow_insert::{
17 insert_record_batch, insert_record_batch_direct, insert_record_batch_reader,
18 insert_record_batches,
19};
20#[cfg(feature = "arrow")]
21use crate::arrow_options::{ArrowOptions, InsertOptions};
22#[cfg(feature = "arrow")]
23use crate::arrow_query_stream::ArrowQueryStream;
24use crate::connection::Connection;
25use crate::error::{Error, Result};
26use crate::format::{InputFormat, OutputFormat};
27use crate::insert_stream::InsertStream;
28use crate::query_param::QueryParams;
29use crate::query_result::QueryResult;
30use crate::query_stream::QueryStream;
31
32/// Builder for creating [`Session`] instances.
33///
34/// `SessionBuilder` provides a fluent API for configuring and creating sessions.
35/// Use [`new`](Self::new) to create a new builder, configure it with the desired
36/// options, and call [`build`](Self::build) to create the session.
37///
38/// # Examples
39///
40/// ```no_run
41/// use chdb_rust::session::SessionBuilder;
42///
43/// // Create a session with default settings
44/// let session = SessionBuilder::new()
45/// .with_data_path("/tmp/mydb")
46/// .with_auto_cleanup(true)
47/// .build()?;
48/// # Ok::<(), chdb_rust::error::Error>(())
49/// ```
50pub struct SessionBuilder<'a> {
51 data_path: PathBuf,
52 default_format: OutputFormat,
53 arguments: Vec<Arg<'a>>,
54 auto_cleanup: bool,
55}
56
57/// A session representing a persistent connection to a chDB database.
58///
59/// A `Session` manages a connection to a persistent database stored on disk.
60/// Unlike stateless queries, sessions allow you to create tables, insert data,
61/// and maintain state across multiple queries.
62///
63/// # Thread Safety
64///
65/// `Session` contains a [`Connection`] which implements
66/// `Send`, so sessions can be safely transferred between threads. However, concurrent
67/// access to the same session should be synchronized.
68///
69/// # Examples
70///
71/// ```no_run
72/// use chdb_rust::session::SessionBuilder;
73/// use chdb_rust::arg::Arg;
74/// use chdb_rust::format::OutputFormat;
75///
76/// let session = SessionBuilder::new()
77/// .with_data_path("/tmp/mydb")
78/// .with_auto_cleanup(true)
79/// .build()?;
80///
81/// // Create a table
82/// session.execute(
83/// "CREATE TABLE users (id UInt64, name String) ENGINE = MergeTree() ORDER BY id",
84/// None
85/// )?;
86///
87/// // Insert data
88/// session.execute("INSERT INTO users VALUES (1, 'Alice')", None)?;
89///
90/// // Query data
91/// let result = session.execute(
92/// "SELECT * FROM users",
93/// Some(&[Arg::OutputFormat(OutputFormat::JSONEachRow)])
94/// )?;
95/// println!("{}", result.data_utf8_lossy());
96/// # Ok::<(), chdb_rust::error::Error>(())
97/// ```
98#[derive(Debug)]
99pub struct Session {
100 /// An `Option` so that [`Drop`] can release the connection before removing
101 /// the directory it was using.
102 conn: Option<Connection>,
103 data_path: PathBuf,
104 default_format: OutputFormat,
105}
106
107impl<'a> SessionBuilder<'a> {
108 /// Create a new `SessionBuilder` with default settings.
109 ///
110 /// The default settings are:
111 /// - Data path: current working directory. The `build` method will create a `chdb`
112 /// subdirectory if the path is not set.
113 /// - Output format: `TabSeparated`
114 /// - Auto cleanup: `false`
115 ///
116 /// # Examples
117 ///
118 /// ```no_run
119 /// use chdb_rust::session::SessionBuilder;
120 ///
121 /// let builder = SessionBuilder::new();
122 /// # Ok::<(), chdb_rust::error::Error>(())
123 /// ```
124 pub fn new() -> Self {
125 Self {
126 data_path: PathBuf::new(),
127 default_format: OutputFormat::TabSeparated,
128 arguments: Vec::new(),
129 auto_cleanup: false,
130 }
131 }
132
133 /// Set the data path for the session.
134 ///
135 /// This specifies the filesystem path where the database will be stored.
136 /// The directory will be created if it doesn't exist.
137 ///
138 /// # Arguments
139 ///
140 /// * `path` - The path where the database should be stored
141 ///
142 /// # Examples
143 ///
144 /// ```no_run
145 /// use chdb_rust::session::SessionBuilder;
146 ///
147 /// let builder = SessionBuilder::new()
148 /// .with_data_path("/tmp/mydb");
149 /// # Ok::<(), chdb_rust::error::Error>(())
150 /// ```
151 pub fn with_data_path(mut self, path: impl Into<PathBuf>) -> Self {
152 self.data_path = path.into();
153 self
154 }
155
156 /// Add a query argument to the session builder.
157 ///
158 /// If `OutputFormat` argument is provided it will be used
159 /// as the default output format for queries executed on this session.
160 ///
161 /// Moreover, `OutputFormat` is consumed by the session layer and is not
162 /// forwarded as a command-line argument to the connection.
163 ///
164 /// # Arguments
165 ///
166 /// * `arg` - The argument to add
167 ///
168 /// # Examples
169 ///
170 /// ```no_run
171 /// use chdb_rust::session::SessionBuilder;
172 /// use chdb_rust::arg::Arg;
173 /// use chdb_rust::format::OutputFormat;
174 /// use std::borrow::Cow;
175 ///
176 /// let builder = SessionBuilder::new()
177 /// .with_arg(Arg::OutputFormat(OutputFormat::JSONEachRow))
178 /// .with_arg(Arg::ConfigFilePath(Cow::from("chdb_ssl.xml")))
179 /// .with_arg(Arg::Custom(Cow::from("progress"), Some(Cow::from("err"))));
180 /// # Ok::<(), chdb_rust::error::Error>(())
181 /// ```
182 /// Custom arguments can be used to specify any additional command-line arguments
183 /// that can be found by running `clickhouse-client --help` in
184 /// the terminal.
185 pub fn with_arg(mut self, arg: Arg<'a>) -> Self {
186 if let Some(fmt) = arg.as_output_format() {
187 self.default_format = fmt;
188 } else {
189 self.arguments.push(arg);
190 }
191 self
192 }
193
194 /// Enable or disable automatic cleanup of the data directory.
195 ///
196 /// If set to `true`, the session will automatically delete the data directory
197 /// when it is dropped. This is useful for temporary databases.
198 ///
199 /// # Arguments
200 ///
201 /// * `value` - Whether to enable automatic cleanup
202 ///
203 /// # Examples
204 ///
205 /// ```no_run
206 /// use chdb_rust::session::SessionBuilder;
207 ///
208 /// // Session will clean up data directory on drop
209 /// let session = SessionBuilder::new()
210 /// .with_data_path("/tmp/tempdb")
211 /// .with_auto_cleanup(true)
212 /// .build()?;
213 /// # Ok::<(), chdb_rust::error::Error>(())
214 /// ```
215 pub fn with_auto_cleanup(mut self, value: bool) -> Self {
216 self.auto_cleanup = value;
217 self
218 }
219
220 /// Build the session with the configured settings.
221 ///
222 /// This creates the data directory if it doesn't exist and establishes
223 /// a connection to the database. All configured arguments are passed to
224 /// the connection.
225 ///
226 /// # Returns
227 ///
228 /// Returns a [`Session`] if successful, or an [`Error`] if
229 /// the session cannot be created.
230 ///
231 /// # Errors
232 ///
233 /// Returns an error if:
234 /// - The data path cannot be created
235 /// - The data path has insufficient permissions
236 /// - The connection cannot be established
237 ///
238 /// # Examples
239 ///
240 /// ```no_run
241 /// use chdb_rust::session::SessionBuilder;
242 ///
243 /// let session = SessionBuilder::new()
244 /// .with_data_path("/tmp/mydb")
245 /// .build()?;
246 /// # Ok::<(), chdb_rust::error::Error>(())
247 /// ```
248 pub fn build(mut self) -> Result<Session> {
249 if self.data_path.as_os_str().is_empty() {
250 let mut default_path = std::env::current_dir()?;
251 default_path.push("chdb");
252 self.data_path = default_path;
253 }
254
255 let dir_already_existed = self.data_path.exists();
256 fs::create_dir_all(&self.data_path)?;
257 let probe_path = self.data_path.join(".write_probe");
258 if let Err(e) = fs::OpenOptions::new()
259 .write(true)
260 .create(true)
261 .truncate(true)
262 .open(&probe_path)
263 {
264 if !dir_already_existed {
265 fs::remove_dir(&self.data_path).ok();
266 }
267 return Err(match e.kind() {
268 io::ErrorKind::PermissionDenied => Error::InsufficientPermissions,
269 _ => Error::Io(e),
270 });
271 }
272 fs::remove_file(&probe_path).ok(); // best-effort cleanup of write probe
273
274 // The engine compares path strings verbatim, so spellings converge
275 // before it sees them: "db", "./db" and "db/" reach it as one string
276 // and share an engine. Only the argument is canonical; data_path stays
277 // as given, so cleanup removes what the caller named rather than what a
278 // symlink pointed at.
279 let canonical = self.data_path.canonicalize()?;
280 let canonical = canonical.to_str().ok_or(Error::PathError)?;
281 let path_arg = format!("--path={canonical}");
282 let owned: Vec<String> = self.arguments.iter().map(|a| a.to_string()).collect();
283 let mut args: Vec<&str> = Vec::with_capacity(1 + owned.len());
284 args.push(&path_arg);
285 args.extend(owned.iter().map(String::as_str));
286
287 let mut conn = Connection::open(&args)?;
288 if self.auto_cleanup {
289 conn.remove_dir_on_last(self.data_path.clone());
290 }
291
292 Ok(Session {
293 conn: Some(conn),
294 data_path: self.data_path,
295 default_format: self.default_format,
296 })
297 }
298}
299
300impl Default for SessionBuilder<'_> {
301 fn default() -> Self {
302 Self::new()
303 }
304}
305
306impl Session {
307 /// Execute a query on this session.
308 ///
309 /// This executes a SQL query against the database associated with this session.
310 /// The query can create tables, insert data, or query existing data.
311 ///
312 /// # Arguments
313 ///
314 /// * `query` - The SQL query string to execute
315 /// * `query_args` - Optional array of query arguments (e.g., output format).
316 ///
317 /// Only `OutputFormat` is currently supported and will override the
318 /// session's default output format for this query.
319 ///
320 /// # Returns
321 ///
322 /// Returns a [`QueryResult`] containing the query output,
323 /// or an [`Error`] if the query fails.
324 ///
325 /// # Examples
326 ///
327 /// ```no_run
328 /// use chdb_rust::session::SessionBuilder;
329 /// use chdb_rust::arg::Arg;
330 /// use chdb_rust::format::OutputFormat;
331 ///
332 /// let session = SessionBuilder::new()
333 /// .with_data_path("/tmp/mydb")
334 /// .with_auto_cleanup(true)
335 /// .build()?;
336 ///
337 /// // Create a table
338 /// session.execute(
339 /// "CREATE TABLE test (id UInt64) ENGINE = MergeTree() ORDER BY id",
340 /// None
341 /// )?;
342 ///
343 /// // Query with JSON output
344 /// let result = session.execute(
345 /// "SELECT * FROM test",
346 /// Some(&[Arg::OutputFormat(OutputFormat::JSONEachRow)])
347 /// )?;
348 /// # Ok::<(), chdb_rust::error::Error>(())
349 /// ```
350 ///
351 /// # Errors
352 ///
353 /// Returns an error if:
354 /// - The query syntax is invalid
355 /// - The query references non-existent tables or columns
356 /// - The query execution fails for any other reason
357 pub fn execute(&self, query: &str, query_args: Option<&[Arg]>) -> Result<QueryResult> {
358 let fmt = extract_output_format(query_args, self.default_format);
359 self.connection().query(query, fmt)
360 }
361
362 /// Execute a query and return a streaming result.
363 ///
364 /// Like [`execute`](Self::execute), but returns a [`QueryStream`] that yields
365 /// result data in chunks instead of materializing the full output at once.
366 ///
367 /// # Arguments
368 ///
369 /// * `query` - The SQL query string to execute
370 /// * `query_args` - Optional array of query arguments (e.g., output format).
371 ///
372 /// Only `OutputFormat` is currently supported and will override the
373 /// session's default output format for this query.
374 ///
375 /// # Returns
376 ///
377 /// Returns a [`QueryStream`] tied to this session's connection, or an [`Error`]
378 /// if the query cannot be started.
379 ///
380 /// # Examples
381 ///
382 /// ```no_run
383 /// use chdb_rust::session::SessionBuilder;
384 /// use chdb_rust::arg::Arg;
385 /// use chdb_rust::format::OutputFormat;
386 ///
387 /// let mut session = SessionBuilder::new()
388 /// .with_data_path("/tmp/mydb")
389 /// .with_auto_cleanup(true)
390 /// .build()?;
391 ///
392 /// let mut stream = session.execute_stream(
393 /// "SELECT number FROM numbers(100_000)",
394 /// Some(&[Arg::OutputFormat(OutputFormat::JSONEachRow)]),
395 /// )?;
396 ///
397 /// while let Some(chunk) = stream.next_chunk()? {
398 /// print!("{}", chunk.data_utf8_lossy());
399 /// }
400 /// # Ok::<(), chdb_rust::error::Error>(())
401 /// ```
402 ///
403 /// # Errors
404 ///
405 /// Returns an error if:
406 /// - The query syntax is invalid
407 /// - The query references non-existent tables or columns
408 /// - The query execution fails for any other reason
409 pub fn execute_stream<'a>(
410 &'a mut self,
411 query: &str,
412 query_args: Option<&[Arg]>,
413 ) -> Result<QueryStream<'a>> {
414 let fmt = extract_output_format(query_args, self.default_format);
415 self.connection_mut().query_stream(query, fmt)
416 }
417
418 /// Execute a query with ClickHouse `{name:Type}` parameter binding and stream the result in chunks.
419 ///
420 /// Like [`Self::execute_stream`], but SQL placeholders are bound from `params`
421 /// before streaming begins. The session is exclusively borrowed for the
422 /// stream's lifetime. Output format may be supplied via `query_args`; other
423 /// [`Arg`] variants are ignored here, matching [`Self::execute_stream`].
424 /// Syntax errors fail when the stream is created. A missing placeholder
425 /// binding is reported on the first [`QueryStream::next_chunk`], not at start.
426 ///
427 /// # Examples
428 ///
429 /// ```no_run
430 /// use chdb_rust::arg::Arg;
431 /// use chdb_rust::format::OutputFormat;
432 /// use chdb_rust::session::SessionBuilder;
433 ///
434 /// let mut session = SessionBuilder::new()
435 /// .with_data_path("/tmp/mydb")
436 /// .with_auto_cleanup(true)
437 /// .build()?;
438 ///
439 /// let mut stream = session.execute_stream_with_params(
440 /// "SELECT {x:UInt64} AS v",
441 /// Some(&[Arg::OutputFormat(OutputFormat::CSV)]),
442 /// [("x", 11_u64)],
443 /// )?;
444 /// while let Some(chunk) = stream.next_chunk()? {
445 /// print!("{}", chunk.data_utf8_lossy());
446 /// }
447 /// # Ok::<(), chdb_rust::error::Error>(())
448 /// ```
449 ///
450 /// # Errors
451 ///
452 /// Returns an error if:
453 /// - The query syntax is invalid
454 /// - The query cannot be started
455 pub fn execute_stream_with_params<'a>(
456 &'a mut self,
457 query: &str,
458 query_args: Option<&[Arg]>,
459 params: impl Into<QueryParams>,
460 ) -> Result<QueryStream<'a>> {
461 let fmt = extract_output_format(query_args, self.default_format);
462 self.connection_mut()
463 .query_stream_with_params(query, fmt, params)
464 }
465
466 /// Open a streaming INSERT on this session's connection.
467 ///
468 /// Session-level counterpart of [`Connection::insert_stream`](crate::connection::Connection::insert_stream).
469 /// The session is exclusively borrowed until the stream is finished, cancelled
470 /// or dropped.
471 ///
472 /// # Errors
473 ///
474 /// Returns an error if the INSERT statement is invalid when the stream is opened.
475 pub fn insert_stream<'a>(
476 &'a mut self,
477 sql: &str,
478 format: InputFormat,
479 ) -> Result<InsertStream<'a>> {
480 self.connection_mut().insert_stream(sql, format)
481 }
482
483 /// Open a streaming INSERT whose statement carries `{name:Type}` placeholders.
484 ///
485 /// Session-level counterpart of
486 /// [`Connection::insert_stream_with_params`](crate::connection::Connection::insert_stream_with_params).
487 pub fn insert_stream_with_params<'a>(
488 &'a mut self,
489 sql: &str,
490 format: InputFormat,
491 params: impl Into<QueryParams>,
492 ) -> Result<InsertStream<'a>> {
493 self.connection_mut()
494 .insert_stream_with_params(sql, format, params)
495 }
496
497 /// Execute a query with ClickHouse `{name:Type}` parameter binding.
498 ///
499 /// Like [`Self::execute`], but SQL placeholders are bound from `params`
500 /// in the chDB library and never interpolated into the SQL text. Output format may
501 /// be supplied via `query_args`; other [`Arg`] variants are ignored here,
502 /// matching [`Self::execute`].
503 ///
504 /// # Examples
505 ///
506 /// ```no_run
507 /// use chdb_rust::arg::Arg;
508 /// use chdb_rust::format::OutputFormat;
509 /// use chdb_rust::session::SessionBuilder;
510 ///
511 /// let session = SessionBuilder::new()
512 /// .with_data_path("/tmp/mydb")
513 /// .with_auto_cleanup(true)
514 /// .build()?;
515 ///
516 /// let result = session.execute_with_params(
517 /// "SELECT {x:UInt64} AS v",
518 /// Some(&[Arg::OutputFormat(OutputFormat::CSV)]),
519 /// [("x", 7_u64)],
520 /// )?;
521 /// # Ok::<(), chdb_rust::error::Error>(())
522 /// ```
523 ///
524 /// # Errors
525 ///
526 /// Returns an error if:
527 /// - The query syntax is invalid
528 /// - A `{name:Type}` placeholder has no matching param
529 /// - A value cannot be parsed as the type declared in the placeholder
530 /// - The query execution fails for any other reason
531 pub fn execute_with_params(
532 &self,
533 query: &str,
534 query_args: Option<&[Arg]>,
535 params: impl Into<QueryParams>,
536 ) -> Result<QueryResult> {
537 let fmt = extract_output_format(query_args, self.default_format);
538 self.connection().query_with_params(query, fmt, params)
539 }
540
541 /// Access the session's [`Connection`] for Arrow registration and low-level queries.
542 pub fn connection(&self) -> &Connection {
543 self.conn
544 .as_ref()
545 .expect("a session holds its connection until it is dropped")
546 }
547
548 /// Access the session's [`Connection`] mutably for APIs that exist only on
549 /// [`Connection`] today (for example [`Connection::query_stream_arrow_with_opts`](crate::connection::Connection::query_stream_arrow_with_opts)).
550 ///
551 /// Streaming query and INSERT methods on [`Session`] borrow the connection
552 /// exclusively while a stream is open because chDB accepts no other
553 /// statement on that connection meanwhile.
554 pub fn connection_mut(&mut self) -> &mut Connection {
555 self.conn
556 .as_mut()
557 .expect("a session holds its connection until it is dropped")
558 }
559
560 /// The data path this session is on, as it was given.
561 pub fn path(&self) -> &Path {
562 &self.data_path
563 }
564
565 /// Closes this session and removes its data directory, whether or not
566 /// [`SessionBuilder::with_auto_cleanup`] was set, and only once this is the
567 /// last handle on the path.
568 ///
569 /// Removal is best effort, as it is on drop: it happens while the engine
570 /// record is locked, so there is no error to hand back.
571 pub fn cleanup(mut self) {
572 let dir = self.data_path.clone();
573 if let Some(conn) = self.conn.as_mut() {
574 conn.remove_dir_on_last(dir);
575 }
576 drop(self.conn.take());
577 }
578
579 /// See [`insert_record_batch`].
580 #[cfg(feature = "arrow")]
581 pub fn insert_record_batch(
582 &self,
583 dest_table: &str,
584 stream_name: &str,
585 batch: RecordBatch,
586 options: InsertOptions,
587 ) -> Result<()> {
588 insert_record_batch(self.connection(), dest_table, stream_name, batch, options)
589 }
590
591 /// See [`insert_record_batch_direct`].
592 #[cfg(feature = "arrow")]
593 pub fn insert_record_batch_direct(
594 &self,
595 dest_table: &str,
596 batch: RecordBatch,
597 options: InsertOptions,
598 ) -> Result<()> {
599 insert_record_batch_direct(self.connection(), dest_table, batch, options)
600 }
601
602 /// See [`insert_record_batches`].
603 #[cfg(feature = "arrow")]
604 pub fn insert_record_batches(
605 &self,
606 dest_table: &str,
607 stream_name: &str,
608 schema: SchemaRef,
609 batches: Vec<RecordBatch>,
610 options: InsertOptions,
611 ) -> Result<()> {
612 insert_record_batches(
613 self.connection(),
614 dest_table,
615 stream_name,
616 schema,
617 batches,
618 options,
619 )
620 }
621
622 /// See [`insert_record_batch_reader`].
623 #[cfg(feature = "arrow")]
624 pub fn insert_record_batch_reader(
625 &self,
626 dest_table: &str,
627 stream_name: &str,
628 reader: Box<dyn RecordBatchReader + Send>,
629 options: InsertOptions,
630 ) -> Result<()> {
631 insert_record_batch_reader(self.connection(), dest_table, stream_name, reader, options)
632 }
633
634 /// Execute a query and stream the result as Arrow record batches.
635 ///
636 /// Session-level counterpart of
637 /// [`Connection::query_stream_arrow`](crate::connection::Connection::query_stream_arrow).
638 ///
639 /// Available when the crate is built with the `arrow` feature.
640 #[cfg(feature = "arrow")]
641 pub fn execute_stream_arrow<'a>(
642 &'a mut self,
643 query: &str,
644 ) -> Result<crate::arrow_query_stream::ArrowQueryStream<'a>> {
645 self.connection_mut().query_stream_arrow(query)
646 }
647
648 /// Execute a query with ClickHouse `{name:Type}` parameter binding and stream Arrow record batches.
649 ///
650 /// Session-level counterpart of
651 /// [`Connection::query_stream_arrow_with_params`](crate::connection::Connection::query_stream_arrow_with_params).
652 /// The session is exclusively borrowed for the stream's lifetime.
653 ///
654 /// Available when the crate is built with the `arrow` feature.
655 ///
656 /// # Examples
657 ///
658 /// ```no_run
659 /// use chdb_rust::session::SessionBuilder;
660 ///
661 /// let mut session = SessionBuilder::new()
662 /// .with_data_path("/tmp/mydb")
663 /// .with_auto_cleanup(true)
664 /// .build()?;
665 ///
666 /// let mut stream = session.execute_stream_arrow_with_params(
667 /// "SELECT {x:UInt64} AS v",
668 /// [("x", 11_u64)],
669 /// None,
670 /// )?;
671 /// while let Some(batch) = stream.next_batch()? {
672 /// println!("rows: {}", batch.num_rows());
673 /// }
674 /// # Ok::<(), chdb_rust::error::Error>(())
675 /// ```
676 ///
677 /// # Errors
678 ///
679 /// Returns an error if:
680 /// - The query syntax is invalid
681 /// - The query cannot be started
682 #[cfg(feature = "arrow")]
683 pub fn execute_stream_arrow_with_params<'a>(
684 &'a mut self,
685 query: &str,
686 params: impl Into<QueryParams>,
687 opts: Option<&ArrowOptions>,
688 ) -> Result<ArrowQueryStream<'a>> {
689 self.connection_mut()
690 .query_stream_arrow_with_params(query, params, opts)
691 }
692}
693
694impl Drop for Session {
695 fn drop(&mut self) {
696 // Releasing the connection is the whole teardown. Whether this was the
697 // last handle, and so whether the directory goes, is decided while the
698 // engine record is locked; deciding it here would race both a fresh
699 // connection on the same path and another session releasing at the same
700 // moment.
701 drop(self.conn.take());
702 }
703}
704
705#[cfg(test)]
706mod test {
707 use crate::test_utils::tempdir;
708
709 use super::*;
710
711 #[test]
712 fn test_session_builder_no_args_still_builds() -> Result<()> {
713 let tmp = tempdir();
714 SessionBuilder::new().with_data_path(tmp.path()).build()?;
715 Ok(())
716 }
717
718 #[test]
719 fn test_query_uses_default_output_format() -> Result<()> {
720 let tmp = tempdir();
721 let session = SessionBuilder::new().with_data_path(tmp.path()).build()?;
722
723 let resp = session.execute("SELECT 'foo' AS name, 1 AS count", None)?;
724
725 assert_eq!(resp.data_utf8_lossy(), "foo\t1\n");
726
727 Ok(())
728 }
729
730 #[test]
731 fn test_query_output_format_overrides_session_builder_output_format() -> Result<()> {
732 let tmp = tempdir();
733 let session = SessionBuilder::new()
734 .with_data_path(tmp.path())
735 .with_arg(Arg::OutputFormat(OutputFormat::Parquet))
736 .build()?;
737
738 let resp = session.execute(
739 "SELECT 1 AS count",
740 Some(&[Arg::OutputFormat(OutputFormat::JSONEachRow)]),
741 )?;
742
743 assert_eq!(resp.data_utf8_lossy(), "{\"count\":1}\n");
744
745 Ok(())
746 }
747}