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
impl Session
Sourcepub fn execute(
&self,
query: &str,
query_args: Option<&[Arg<'_>]>,
) -> Result<QueryResult>
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 executequery_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
Sourcepub fn execute_stream<'a>(
&'a mut self,
query: &str,
query_args: Option<&[Arg<'_>]>,
) -> Result<QueryStream<'a>>
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 executequery_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
Sourcepub fn execute_stream_with_params<'a>(
&'a mut self,
query: &str,
query_args: Option<&[Arg<'_>]>,
params: impl Into<QueryParams>,
) -> Result<QueryStream<'a>>
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
Sourcepub fn insert_stream<'a>(
&'a mut self,
sql: &str,
format: InputFormat,
) -> Result<InsertStream<'a>>
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.
Sourcepub fn insert_stream_with_params<'a>(
&'a mut self,
sql: &str,
format: InputFormat,
params: impl Into<QueryParams>,
) -> Result<InsertStream<'a>>
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.
Sourcepub fn execute_with_params(
&self,
query: &str,
query_args: Option<&[Arg<'_>]>,
params: impl Into<QueryParams>,
) -> Result<QueryResult>
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
Sourcepub fn connection(&self) -> &Connection
pub fn connection(&self) -> &Connection
Access the session’s Connection for Arrow registration and low-level queries.
Sourcepub fn connection_mut(&mut self) -> &mut Connection
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.
Sourcepub fn cleanup(self)
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.
Sourcepub fn insert_record_batch(
&self,
dest_table: &str,
stream_name: &str,
batch: RecordBatch,
options: InsertOptions,
) -> Result<()>
pub fn insert_record_batch( &self, dest_table: &str, stream_name: &str, batch: RecordBatch, options: InsertOptions, ) -> Result<()>
See insert_record_batch.
Sourcepub fn insert_record_batch_direct(
&self,
dest_table: &str,
batch: RecordBatch,
options: InsertOptions,
) -> Result<()>
pub fn insert_record_batch_direct( &self, dest_table: &str, batch: RecordBatch, options: InsertOptions, ) -> Result<()>
Sourcepub fn insert_record_batches(
&self,
dest_table: &str,
stream_name: &str,
schema: SchemaRef,
batches: Vec<RecordBatch>,
options: InsertOptions,
) -> Result<()>
pub fn insert_record_batches( &self, dest_table: &str, stream_name: &str, schema: SchemaRef, batches: Vec<RecordBatch>, options: InsertOptions, ) -> Result<()>
Sourcepub fn insert_record_batch_reader(
&self,
dest_table: &str,
stream_name: &str,
reader: Box<dyn RecordBatchReader + Send>,
options: InsertOptions,
) -> Result<()>
pub fn insert_record_batch_reader( &self, dest_table: &str, stream_name: &str, reader: Box<dyn RecordBatchReader + Send>, options: InsertOptions, ) -> Result<()>
Sourcepub fn execute_stream_arrow<'a>(
&'a mut self,
query: &str,
) -> Result<ArrowQueryStream<'a>>
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.
Sourcepub fn execute_stream_arrow_with_params<'a>(
&'a mut self,
query: &str,
params: impl Into<QueryParams>,
opts: Option<&ArrowOptions>,
) -> Result<ArrowQueryStream<'a>>
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