Skip to main content

Session

Struct Session 

Source
pub struct Session { /* private fields */ }
Expand description

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

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());

Implementations§

Source§

impl Session

Source

pub fn execute( &self, query: &str, query_args: Option<&[Arg<'_>]>, ) -> Result<QueryResult>

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
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)])
)?;
§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
Source

pub fn execute_stream<'a>( &'a mut self, query: &str, query_args: Option<&[Arg<'_>]>, ) -> Result<QueryStream<'a>>

Execute a query and return a streaming result.

Like 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
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());
}
§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
Source

pub fn execute_stream_with_params<'a>( &'a mut self, query: &str, query_args: Option<&[Arg<'_>]>, params: impl Into<QueryParams>, ) -> Result<QueryStream<'a>>

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
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());
}
§Errors

Returns an error if:

  • The query syntax is invalid
  • The query cannot be started
Source

pub fn insert_stream<'a>( &'a mut self, sql: &str, format: InputFormat, ) -> Result<InsertStream<'a>>

Open a streaming INSERT on this session’s connection.

Session-level counterpart of 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.

Source

pub fn insert_stream_with_params<'a>( &'a mut self, sql: &str, format: InputFormat, params: impl Into<QueryParams>, ) -> Result<InsertStream<'a>>

Open a streaming INSERT whose statement carries {name:Type} placeholders.

Session-level counterpart of Connection::insert_stream_with_params.

Source

pub fn execute_with_params( &self, query: &str, query_args: Option<&[Arg<'_>]>, params: impl Into<QueryParams>, ) -> Result<QueryResult>

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
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)],
)?;
§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
Source

pub fn connection(&self) -> &Connection

Access the session’s Connection for Arrow registration and low-level queries.

Source

pub fn connection_mut(&mut self) -> &mut Connection

Access the session’s Connection mutably for APIs that exist only on Connection today (for example 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.

Source

pub fn path(&self) -> &Path

The data path this session is on, as it was given.

Source

pub fn cleanup(self)

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.

Source

pub fn insert_record_batch( &self, dest_table: &str, stream_name: &str, batch: RecordBatch, options: InsertOptions, ) -> Result<()>

Source

pub fn insert_record_batch_direct( &self, dest_table: &str, batch: RecordBatch, options: InsertOptions, ) -> Result<()>

Source

pub fn insert_record_batches( &self, dest_table: &str, stream_name: &str, schema: SchemaRef, batches: Vec<RecordBatch>, options: InsertOptions, ) -> Result<()>

Source

pub fn insert_record_batch_reader( &self, dest_table: &str, stream_name: &str, reader: Box<dyn RecordBatchReader + Send>, options: InsertOptions, ) -> Result<()>

Source

pub fn execute_stream_arrow<'a>( &'a mut self, query: &str, ) -> Result<ArrowQueryStream<'a>>

Execute a query and stream the result as Arrow record batches.

Session-level counterpart of Connection::query_stream_arrow.

Available when the crate is built with the arrow feature.

Source

pub fn execute_stream_arrow_with_params<'a>( &'a mut self, query: &str, params: impl Into<QueryParams>, opts: Option<&ArrowOptions>, ) -> Result<ArrowQueryStream<'a>>

Execute a query with ClickHouse {name:Type} parameter binding and stream Arrow record batches.

Session-level counterpart of 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
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());
}
§Errors

Returns an error if:

  • The query syntax is invalid
  • The query cannot be started

Trait Implementations§

Source§

impl Debug for Session

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Session

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.