Client

Struct Client 

Source
pub struct Client<T: ClientFormat> {
    pub client_id: u16,
    /* private fields */
}
Expand description

A thread-safe handle for interacting with a ClickHouse database over its native protocol.

The Client struct is the primary interface for executing queries, inserting data, and managing database schemas. It supports two data formats:

Client instances are lightweight and can be cloned and shared across threads. Each instance maintains a reference to an underlying connection, which is managed automatically. The client also supports event subscription for receiving progress and profiling information from ClickHouse.

§Usage

Create a Client using the ClientBuilder for a fluent configuration experience, or use Client::connect for direct connection setup.

§Examples

use clickhouse_arrow::prelude::*;
use clickhouse_arrow::arrow;
use futures_util::StreamExt;

let client = Client::builder()
    .destination("localhost:9000")
    .username("default")
    .build::<ArrowFormat>()
    .await?;

// Execute a query
let batch = client
    .query("SELECT 1")
    .await?
    .collect::<Vec<_>>()
    .await
    .into_iter()
    .collect::<Result<Vec<_>>>()?;
arrow::util::pretty::print_batches(batch)?;

Fields§

§client_id: u16

Implementations§

Source§

impl<T: ClientFormat> Client<T>

Source

pub fn builder() -> ClientBuilder

Get an instance of ClientBuilder which allows creating a Client using a builder Creates a new ClientBuilder for configuring and building a ClickHouse client.

This method provides a fluent interface to set up a Client with custom connection parameters, such as the server address, credentials, TLS, and compression. The builder can create either a single Client or a connection pool (with the pool feature enabled).

Use this method when you need fine-grained control over the client configuration. For simple connections, you can also use Client::connect directly.

§Returns

A ClientBuilder instance ready for configuration.

§Examples
use clickhouse_arrow::prelude::*;

let builder = Client::builder()
    .with_endpoint("localhost:9000")
    .with_username("default")
    .with_password("");
Source

pub async fn connect<A: Into<Destination>>( destination: A, options: ClientOptions, settings: Option<Arc<Settings>>, context: Option<ConnectionContext>, ) -> Result<Self>

Establishes a connection to a ClickHouse server over TCP, with optional TLS support.

This method creates a new Client instance connected to the specified destination. The connection can be configured using ClientOptions, which allows setting parameters like username, password, TLS, and compression. Optional settings can be provided to customize ClickHouse session behavior, and a context can be used for tracing or cloud-specific configurations.

§Parameters
  • destination: The ClickHouse server address (e.g., "localhost:9000" or a Destination).
  • options: Configuration for the connection, including credentials, TLS, and cloud settings.
  • settings: Optional ClickHouse session settings (e.g., query timeouts, max rows).
  • context: Optional connection context for tracing or cloud-specific behavior.
§Returns

A Result containing the connected Client instance, or an error if the connection fails.

§Errors
  • Fails if the destination cannot be resolved or the connection cannot be established.
  • Fails if authentication or TLS setup encounters an issue.
§Examples
use clickhouse_arrow::client::{Client, ClientOptions};

let options = ClientOptions::default()
    .username("default")
    .password("")
    .use_tls(false);

let client = Client::connect("localhost:9000", options, None, None).await?;
Source

pub fn status(&self) -> ConnectionStatus

Retrieves the status of the underlying ClickHouse connection.

This method returns the current ConnectionStatus of the client’s connection, indicating whether it is active, idle, or disconnected. Useful for monitoring the health of the connection before executing queries.

§Returns

A ConnectionStatus enum describing the connection state.

§Examples
use clickhouse_arrow::prelude::*;

let client = Client::<ArrowFormat>::builder()
    .with_endpoint("localhost:9000")
    .build()
    .await
    .unwrap();

let status = client.status();
println!("Connection status: {status:?}");
Source

pub fn subscribe_events(&self) -> Receiver<Event>

Subscribes to progress and profile events from ClickHouse queries.

This method returns a broadcast::Receiver that delivers Event instances containing progress updates (Progress) or profiling information (ProfileEvent) as queries execute. Events are generated asynchronously and can be used to monitor query execution in real time.

§Returns

A broadcast::Receiver<Event> for receiving ClickHouse events.

§Examples
use clickhouse_arrow::prelude::*;
use tokio::sync::broadcast::error::RecvError;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

let mut receiver = client.subscribe_events();
let handle = tokio::spawn(async move {
    while let Ok(event) = receiver.recv().await {
        println!("Received event: {:?}", event);
    }
});

// Execute a query to generate events
client.query("SELECT * FROM large_table").await.unwrap();
Source

pub async fn health_check(&self, ping: bool) -> Result<()>

Checks the health of the underlying ClickHouse connection.

This method verifies that the connection is active and responsive. If ping is true, it sends a lightweight ping to the ClickHouse server to confirm connectivity. Otherwise, it checks the connection’s internal state.

§Parameters
  • ping: If true, performs an active ping to the server; if false, checks the connection state without network activity.
§Returns

A Result indicating whether the connection is healthy.

§Errors
  • Fails if the connection is disconnected or unresponsive.
  • Fails if the ping operation times out or encounters a network error.
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build::<ArrowFormat>()
    .await
    .unwrap();

client.health_check(true).await.unwrap();
println!("Connection is healthy!");
Source

pub async fn shutdown(&self) -> Result<()>

Shuts down the ClickHouse client and closes its connection.

This method gracefully terminates the underlying connection, ensuring that any pending operations are completed or canceled. After shutdown, the client cannot be used for further operations.

§Returns

A Result indicating whether the shutdown was successful.

§Errors
  • Fails if the connection cannot be closed due to network issues or internal errors.
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build::<ArrowFormat>()
    .await
    .unwrap();

client.shutdown().await.unwrap();
println!("Client shut down successfully!");
Source

pub async fn insert( &self, query: impl Into<ParsedQuery>, block: T::Data, qid: Option<Qid>, ) -> Result<impl Stream<Item = Result<()>> + '_>

Inserts a block of data into ClickHouse using the native protocol.

This method sends an insert query with a single block of data, formatted according to the client’s data format (T: ClientFormat). For NativeClient, the data is a Block; for ArrowClient, it is a RecordBatch. The query is executed asynchronously, and any response data, progress events, or errors are streamed back.

Progress and profile events are dispatched to the client’s event channel (see Client::subscribe_events). The returned stream yields () on success or an error if the insert fails.

§Parameters
  • query: The insert query (e.g., "INSERT INTO my_table VALUES").
  • block: The data to insert, in the format specified by T (Block or RecordBatch).
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing a stream of Result<()>, where each item indicates the success or failure of processing response data.

§Errors
  • Fails if the query is malformed or the data format is invalid.
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., schema mismatch).
§Examples
use clickhouse_arrow::prelude::*;
use arrow::record_batch::RecordBatch;

let client = Client::builder()
    .destination("localhost:9000")
    .build_arrow()
    .await?;

let qid = Qid::new();
// Assume `batch` is a valid RecordBatch
let batch: RecordBatch = // ...;
let stream = client.insert("INSERT INTO my_table VALUES", batch, Some(qid)).await?;
while let Some(result) = stream.next().await {
    result?; // Check for errors
}
Source

pub async fn insert_many( &self, query: impl Into<ParsedQuery>, batch: Vec<T::Data>, qid: Option<Qid>, ) -> Result<impl Stream<Item = Result<()>> + '_>

Inserts multiple blocks of data into ClickHouse using the native protocol.

This method sends an insert query with a collection of data blocks, formatted according to the client’s data format (T: ClientFormat). For NativeClient, the data is a Vec<Block>; for ArrowClient, it is a Vec<RecordBatch>. The query is executed asynchronously, and any response data, progress events, or errors are streamed back.

Progress and profile events are dispatched to the client’s event channel (see Client::subscribe_events). The returned stream yields () on success or an error if the insert fails. Use this method when inserting multiple batches of data to reduce overhead compared to multiple Client::insert calls.

§Parameters
  • query: The insert query (e.g., "INSERT INTO my_table VALUES").
  • batch: A vector of data blocks to insert, in the format specified by T.
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing a stream of Result<()>, where each item indicates the success or failure of processing response data.

§Errors
  • Fails if the query is malformed or any data block is invalid.
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., schema mismatch).
§Examples
use clickhouse_arrow::prelude::*;
use arrow::record_batch::RecordBatch;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build::<ArrowFormat>()
    .await
    .unwrap();

// Assume `batches` is a Vec<RecordBatch>
let batches: Vec<RecordBatch> = vec![/* ... */];
let stream = client.insert_many("INSERT INTO my_table VALUES", batches, None).await.unwrap();
while let Some(result) = stream.next().await {
    result.unwrap(); // Check for errors
}
Source

pub async fn query_raw<P: Into<QueryParams>>( &self, query: String, params: Option<P>, qid: Qid, ) -> Result<impl Stream<Item = Result<T::Data>> + 'static>

Executes a raw ClickHouse query and streams raw data in the client’s format.

This method sends a query to ClickHouse and returns a stream of raw data blocks in the format specified by T: ClientFormat (Block for NativeClient, RecordBatch for ArrowClient). It is a low-level method suitable for custom processing of query results. For higher-level interfaces, consider Client::query or Client::query_rows.

Progress and profile events are dispatched to the client’s event channel (see Client::subscribe_events).

§Parameters
  • query: The SQL query to execute (e.g., "SELECT * FROM my_table").
  • qid: A unique query ID for tracking and debugging.
§Returns

A Result containing a stream of Result<T::Data>, where each item is a data block or an error.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., table not found).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build::<ArrowFormat>()
    .await
    .unwrap();

let qid = Qid::new();
let mut stream = client.query_raw("SELECT * FROM my_table", qid).await.unwrap();
while let Some(block) = stream.next().await {
    let batch = block.unwrap();
    println!("Received batch with {} rows", batch.num_rows());
}
Source

pub async fn execute( &self, query: impl Into<ParsedQuery>, qid: Option<Qid>, ) -> Result<()>

Executes a ClickHouse query and discards all returned data.

This method sends a query to ClickHouse and processes the response stream to check for errors, but discards any returned data blocks. It is useful for queries that modify data (e.g., INSERT, UPDATE, DELETE) or DDL statements where the result data is not needed. For queries that return data, use Client::query or Client::query_raw.

§Parameters
  • query: The SQL query to execute (e.g., "DROP TABLE my_table").
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result indicating whether the query executed successfully.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., permission denied).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

client.execute("DROP TABLE IF EXISTS my_table", None).await.unwrap();
println!("Table dropped successfully!");
Source

pub async fn execute_params<P: Into<QueryParams>>( &self, query: impl Into<ParsedQuery>, params: Option<P>, qid: Option<Qid>, ) -> Result<()>

Executes a ClickHouse query with query parameters and discards all returned data.

§Parameters
  • query: The SQL query to execute (e.g., "DROP TABLE my_table").
  • params: The query parameters to provide
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result indicating whether the query executed successfully.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., permission denied).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

let params = Some(vec![
    ("str", ParamValue::from("hello")),
    ("num", ParamValue::from(42)),
    ("array", ParamValue::from("['a', 'b', 'c']")),
]);
let query = "SELECT {num:Int64}, {str:String}, {array:Array(String)}";
client.execute_params(query, params, None).await.unwrap();
println!("Table dropped successfully!");
Source

pub async fn execute_now( &self, query: impl Into<ParsedQuery>, qid: Option<Qid>, ) -> Result<()>

Executes a ClickHouse query without processing the response stream.

This method sends a query to ClickHouse and immediately discards the response stream without checking for errors or processing data. It is a lightweight alternative to Client::execute, suitable for fire-and-forget scenarios where the query’s outcome is not critical. For safer execution, use Client::execute.

§Parameters
  • query: The SQL query to execute (e.g., "INSERT INTO my_table VALUES (1)").
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result indicating whether the query was sent successfully.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if the connection to ClickHouse is interrupted.
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build::<ArrowFormat>()
    .await
    .unwrap();

client.execute_now("INSERT INTO logs VALUES ('event')", None).await.unwrap();
println!("Log event sent!");
Source

pub async fn execute_now_params<P: Into<QueryParams>>( &self, query: impl Into<ParsedQuery>, params: Option<P>, qid: Option<Qid>, ) -> Result<()>

Executes a ClickHouse query with query parameters without processing the response stream.

§Parameters
  • query: The SQL query to execute (e.g., "INSERT INTO my_table VALUES (1)").
  • params: The query parameters to provide
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result indicating whether the query was sent successfully.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if the connection to ClickHouse is interrupted.
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build::<ArrowFormat>()
    .await
    .unwrap();


let params = Some(vec![("str", ParamValue::from("hello"))]);
let query = "INSERT INTO logs VALUES ({str:String})";
client.execute_now_params(query, params, None).await.unwrap();
println!("Log event sent!");
Source

pub async fn create_database( &self, database: Option<&str>, qid: Option<Qid>, ) -> Result<()>

Creates a new database in ClickHouse using a DDL statement.

This method issues a CREATE DATABASE statement for the specified database. If no database is provided, it uses the client’s default database from the connection metadata. The default database cannot be created, as it is reserved by ClickHouse.

§Parameters
  • database: Optional name of the database to create. If None, uses the client’s default database.
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result indicating success or failure of the operation.

§Errors
  • Fails if the database name is invalid or reserved (e.g., default).
  • Fails if the query execution encounters a ClickHouse error.
  • Fails if the connection is interrupted.
§Examples
use clickhouse_arrow::client::{Client, ClientBuilder};

let client = ClientBuilder::new()
    .destination("localhost:9000")
    .build_native()
    .await?;

client.create_database(Some("my_db"), None).await?;
Source

pub async fn drop_database( &self, database: &str, sync: bool, qid: Option<Qid>, ) -> Result<()>

Drops a database in ClickHouse using a DDL statement.

This method issues a DROP DATABASE statement for the specified database. The default database cannot be dropped, as it is reserved by ClickHouse. If the client is connected to a non-default database, dropping a different database is not allowed to prevent accidental data loss.

§Parameters
  • database: Name of the database to drop.
  • sync: If true, the operation waits for ClickHouse to complete the drop synchronously.
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result indicating success or failure of the operation.

§Errors
  • Fails if the database is default (reserved).
  • Fails if the client is connected to a non-default database different from database.
  • Fails if the query execution encounters a ClickHouse error.
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .destination("localhost:9000")
    .database("default") // Must be connected to default to drop 'other' databases
    .build::<NativeFormat>()
    .await?;

client.drop_database("my_db", true, None).await?;
Source§

impl Client<NativeFormat>

Source

pub async fn insert_rows<T: Row + Send + 'static>( &self, query: impl Into<ParsedQuery>, blocks: impl Iterator<Item = T> + Send + Sync + 'static, qid: Option<Qid>, ) -> Result<ClickHouseResponse<()>>

Inserts rows into ClickHouse using the native protocol.

This method sends an insert query with a collection of rows, where each row is a type T implementing Row. The rows are converted into a ClickHouse Block and sent over the native protocol. The query is executed asynchronously, and any response data, progress events, or errors are streamed back.

Progress and profile events are dispatched to the client’s event channel (see Client::subscribe_events). The returned ClickHouseResponse yields () on success or an error if the insert fails.

§Parameters
  • query: The insert query (e.g., "INSERT INTO my_table VALUES").
  • blocks: An iterator of rows to insert, where each row implements Row.
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing a ClickHouseResponse<()> that streams the operation’s outcome.

§Errors
  • Fails if the query is malformed or the row data is invalid.
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., schema mismatch).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_native()
    .await
    .unwrap();

// Assume `MyRow` implements `Row`
let rows = vec![MyRow { /* ... */ }, MyRow { /* ... */ }];
let response = client.insert_rows("INSERT INTO my_table VALUES", rows.into_iter(), None)
    .await
    .unwrap();
while let Some(result) = response.next().await {
    result.unwrap(); // Check for errors
}
Source

pub async fn query<T: Row + Send + 'static>( &self, query: impl Into<ParsedQuery>, qid: Option<Qid>, ) -> Result<ClickHouseResponse<T>>

Executes a ClickHouse query and streams deserialized rows.

This method sends a query to ClickHouse and returns a stream of rows, where each row is deserialized into type T implementing Row. Rows are grouped into ClickHouse blocks, and the stream yields rows as they are received. Use this method for type-safe access to query results in native format.

Progress and profile events are dispatched to the client’s event channel (see Client::subscribe_events).

§Parameters
  • query: The SQL query to execute (e.g., "SELECT * FROM my_table").
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing a ClickHouseResponse<T> that streams deserialized rows of type T.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if row deserialization fails (e.g., schema mismatch).
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., table not found).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_native()
    .await
    .unwrap();

// Assume `MyRow` implements `Row`
let mut response = client.query::<MyRow>("SELECT * FROM my_table", None).await.unwrap();
while let Some(row) = response.next().await {
    let row = row.unwrap();
    println!("Row: {:?}", row);
}
Source

pub async fn query_params<T: Row + Send + 'static>( &self, query: impl Into<ParsedQuery>, params: Option<QueryParams>, qid: Option<Qid>, ) -> Result<ClickHouseResponse<T>>

Executes a ClickHouse query with parameters and streams deserialized rows.

§Parameters
  • query: The SQL query to execute (e.g., "SELECT * FROM my_table").
  • params: The query parameters to provide
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing a ClickHouseResponse<T> that streams deserialized rows of type T.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if row deserialization fails (e.g., schema mismatch).
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., table not found).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_native()
    .await
    .unwrap();

// Assume `MyRow` implements `Row`
let params = Some(vec![("name", ParamValue::from("my_table"))]);
let query = "SELECT * FROM {name:Identifier}";
let mut response = client.query_params::<MyRow>(query, params, None).await.unwrap();
while let Some(row) = response.next().await {
    let row = row.unwrap();
    println!("Row: {:?}", row);
}
Source

pub async fn query_one<T: Row + Send + 'static>( &self, query: impl Into<ParsedQuery>, qid: Option<Qid>, ) -> Result<Option<T>>

Executes a ClickHouse query and returns the first row, discarding the rest.

This method sends a query to ClickHouse and returns the first row deserialized into type T implementing Row, or None if the result is empty. It is useful for queries expected to return a single row (e.g., SELECT COUNT(*)). For streaming multiple rows, use Client::query.

Progress and profile events are dispatched to the client’s event channel (see Client::subscribe_events).

§Parameters
  • query: The SQL query to execute (e.g., "SELECT name FROM users WHERE id = 1").
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing an Option<T>, where T is the deserialized row, or None if no rows are returned.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if row deserialization fails (e.g., schema mismatch).
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., table not found).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_native()
    .await
    .unwrap();

// Assume `MyRow` implements `Row`
let row = client.query_one::<MyRow>("SELECT name FROM users WHERE id = 1", None)
    .await
    .unwrap();
if let Some(row) = row {
    println!("Found row: {:?}", row);
}
Source

pub async fn query_one_params<T: Row + Send + 'static>( &self, query: impl Into<ParsedQuery>, params: Option<QueryParams>, qid: Option<Qid>, ) -> Result<Option<T>>

Executes a ClickHouse query with parameters and returns the first row, discarding the rest.

§Parameters
  • query: The SQL query to execute (e.g., "SELECT name FROM users WHERE id = 1").
  • params: The query parameters to provide
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing an Option<T>, where T is the deserialized row, or None if no rows are returned.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if row deserialization fails (e.g., schema mismatch).
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., table not found).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_native()
    .await
    .unwrap();

// Assume `MyRow` implements `Row`
let params = Some(vec![
    ("str", ParamValue::from("name")),
].into());
let query = "SELECT {str:String} FROM users WHERE id = 1";
let row = client.query_one_params::<MyRow>(query, params, None)
    .await
    .unwrap();
if let Some(row) = row {
    println!("Found row: {:?}", row);
}
Source

pub async fn create_table<T: Row>( &self, database: Option<&str>, table: &str, options: &CreateOptions, qid: Option<Qid>, ) -> Result<()>

Creates a ClickHouse table from a Rust struct that implements the Row trait.

This method generates and executes a CREATE TABLE DDL statement based on the structure of the provided Row type. The table schema is automatically derived from the struct fields and their types.

§Arguments
  • database - Optional database name. If None, uses the client’s default database
  • table - The name of the table to create
  • options - Table creation options including engine type, order by, and partition by
  • query_id - Optional query ID for tracking and debugging
§Type Parameters
  • T - A type that implements the Row trait, typically a struct with the #[derive(Row)] macro
§Example
#[derive(Row)]
struct User {
    id: u32,
    name: String,
    created_at: DateTime,
}

let options = CreateOptions::new("MergeTree")
    .with_order_by(&["id"]);

client.create_table::<User>(Some("analytics"), "users", &options, None).await?;
§Errors
  • Returns an error if the table creation fails
  • Returns an error if the database/table names are invalid
  • Returns an error if the connection is lost
Source§

impl Client<ArrowFormat>

Source

pub async fn query( &self, query: impl Into<ParsedQuery>, qid: Option<Qid>, ) -> Result<ClickHouseResponse<RecordBatch>>

Executes a ClickHouse query and streams Arrow RecordBatch results.

This method sends a query to ClickHouse and returns a stream of RecordBatch instances, each containing a chunk of the query results in Apache Arrow format. Use this method for efficient integration with Arrow-based data processing pipelines. For row-based access, consider Client::query_rows.

Progress and profile events are dispatched to the client’s event channel (see Client::subscribe_events).

§Parameters
  • query: The SQL query to execute (e.g., "SELECT * FROM my_table").
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing a ClickHouseResponse<RecordBatch> that streams query results.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., table not found).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

let mut response = client.query("SELECT * FROM my_table", None).await.unwrap();
while let Some(batch) = response.next().await {
    let batch = batch.unwrap();
    println!("Received batch with {} rows", batch.num_rows());
}
Source

pub async fn query_params( &self, query: impl Into<ParsedQuery>, params: Option<QueryParams>, qid: Option<Qid>, ) -> Result<ClickHouseResponse<RecordBatch>>

Executes a ClickHouse query with parameters and streams Arrow RecordBatch results.

§Parameters
  • query: The SQL query to execute (e.g., "SELECT * FROM my_table").
  • params: The query parameters to provide
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing a ClickHouseResponse<RecordBatch> that streams query results.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., table not found).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

let params = Some(vec![("name", ParamValue::from("my_table"))].into());
let query = "SELECT * FROM {name:Identifier}";
let mut response = client.query_params(query, params, None).await.unwrap();
while let Some(batch) = response.next().await {
    let batch = batch.unwrap();
    println!("Received batch with {} rows", batch.num_rows());
}
Source

pub async fn query_rows( &self, query: impl Into<ParsedQuery>, qid: Option<Qid>, ) -> Result<ClickHouseResponse<Vec<Value>>>

Executes a ClickHouse query and streams rows as column-major values.

This method sends a query to ClickHouse and returns a stream of rows, where each row is represented as a Vec<Value> containing column values. The data is transposed from Arrow RecordBatch format to row-major format, making it convenient for row-based processing. For direct Arrow access, use Client::query.

Progress and profile events are dispatched to the client’s event channel (see Client::subscribe_events).

§Parameters
  • query: The SQL query to execute (e.g., "SELECT * FROM my_table").
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing a ClickHouseResponse<Vec<Value>> that streams rows.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., table not found).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

let mut response = client.query_rows("SELECT * FROM my_table", None).await.unwrap();
while let Some(row) = response.next().await {
    let row = row.unwrap();
    println!("Row values: {:?}", row);
}
Source

pub async fn query_column( &self, query: impl Into<ParsedQuery>, qid: Option<Qid>, ) -> Result<Option<ArrayRef>>

Executes a ClickHouse query and returns the first column of the first batch.

This method sends a query to ClickHouse and returns the first column of the first RecordBatch as an Arrow ArrayRef, or None if the result is empty. It is useful for queries that return a single column (e.g., SELECT id FROM my_table). For full batch access, use Client::query.

Progress and profile events are dispatched to the client’s event channel (see Client::subscribe_events).

§Parameters
  • query: The SQL query to execute (e.g., "SELECT id FROM my_table").
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing an Option<ArrayRef>, representing the first column of the first batch, or None if no data is returned.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., table not found).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

let column = client.query_column("SELECT id FROM my_table", None)
    .await
    .unwrap();
if let Some(col) = column {
    println!("Column data: {:?}", col);
}
Source

pub async fn query_column_params( &self, query: impl Into<ParsedQuery>, params: Option<QueryParams>, qid: Option<Qid>, ) -> Result<Option<ArrayRef>>

Executes a ClickHouse query with parameters and returns the first column of the first batch.

§Parameters
  • query: The SQL query to execute (e.g., "SELECT id FROM my_table").
  • params: The query parameters to provide
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing an Option<ArrayRef>, representing the first column of the first batch, or None if no data is returned.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., table not found).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

let params = Some(vec![("name", ParamValue::from("my_table"))].into());
let query = "SELECT id FROM {name:Identifier}";
let column = client.query_column_params("SELECT id FROM my_table", params, None)
    .await
    .unwrap();
if let Some(col) = column {
    println!("Column data: {:?}", col);
}
Source

pub async fn query_one( &self, query: impl Into<ParsedQuery>, qid: Option<Qid>, ) -> Result<Option<RecordBatch>>

Executes a ClickHouse query and returns the first row as a RecordBatch.

This method sends a query to ClickHouse and returns the first row of the first RecordBatch, or None if the result is empty. The returned RecordBatch contains a single row. It is useful for queries expected to return a single row (e.g., SELECT * FROM users WHERE id = 1). For streaming multiple rows, use Client::query.

Progress and profile events are dispatched to the client’s event channel (see Client::subscribe_events).

§Parameters
  • query: The SQL query to execute (e.g., "SELECT * FROM users WHERE id = 1").
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing an Option<RecordBatch>, representing the first row, or None if no rows are returned.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., table not found).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

let batch = client.query_one("SELECT * FROM users WHERE id = 1", None)
    .await
    .unwrap();
if let Some(row) = batch {
    println!("Row data: {:?}", row);
}
Source

pub async fn query_one_params( &self, query: impl Into<ParsedQuery>, params: Option<QueryParams>, qid: Option<Qid>, ) -> Result<Option<RecordBatch>>

Executes a ClickHouse query with parameters and returns the first row as a RecordBatch.

§Parameters
  • query: The SQL query to execute (e.g., "SELECT * FROM users WHERE id = 1").
  • params: The query parameters to provide
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing an Option<RecordBatch>, representing the first row, or None if no rows are returned.

§Errors
  • Fails if the query is malformed or unsupported by ClickHouse.
  • Fails if the connection to ClickHouse is interrupted.
  • Fails if ClickHouse returns an exception (e.g., table not found).
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

let params = Some(vec![("id", ParamValue::from(1))]);
let batch = client.query_one_params("SELECT * FROM users WHERE id = {id:UInt64}", None)
    .await
    .unwrap();
if let Some(row) = batch {
    println!("Row data: {:?}", row);
}
Source

pub async fn fetch_schemas(&self, qid: Option<Qid>) -> Result<Vec<String>>

Fetches the list of database names (schemas) in ClickHouse.

This method queries ClickHouse to retrieve the names of all databases accessible to the client. It is useful for exploring the database structure or validating database existence before performing operations.

§Parameters
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing a Vec<String> of database names.

§Errors
  • Fails if the query execution encounters a ClickHouse error (e.g., permission denied).
  • Fails if the connection to ClickHouse is interrupted.
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

let schemas = client.fetch_schemas(None).await.unwrap();
println!("Databases: {:?}", schemas);
Source

pub async fn fetch_all_tables( &self, qid: Option<Qid>, ) -> Result<HashMap<String, Vec<String>>>

Fetches all tables across all databases in ClickHouse.

This method queries ClickHouse to retrieve a mapping of database names to their table names. It is useful for discovering the full schema structure of the ClickHouse instance.

§Parameters
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing a HashMap<String, Vec<String>>, where each key is a database name and the value is a list of table names in that database.

§Errors
  • Fails if the query execution encounters a ClickHouse error (e.g., permission denied).
  • Fails if the connection to ClickHouse is interrupted.
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

let tables = client.fetch_all_tables(None).await.unwrap();
for (db, tables) in tables {
    println!("Database {} has tables: {:?}", db, tables);
}
Source

pub async fn fetch_tables( &self, database: Option<&str>, qid: Option<Qid>, ) -> Result<Vec<String>>

Fetches the list of table names in a specific ClickHouse database.

This method queries ClickHouse to retrieve the names of all tables in the specified database (or the client’s default database if None). It is useful for exploring the schema of a specific database.

§Parameters
  • database: Optional database name. If None, uses the client’s default database.
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing a Vec<String> of table names.

§Errors
  • Fails if the database does not exist or is inaccessible.
  • Fails if the query execution encounters a ClickHouse error (e.g., permission denied).
  • Fails if the connection to ClickHouse is interrupted.
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

let tables = client.fetch_tables(Some("my_db"), None).await.unwrap();
println!("Tables in my_db: {:?}", tables);
Source

pub async fn fetch_schema( &self, database: Option<&str>, tables: &[&str], qid: Option<Qid>, ) -> Result<HashMap<String, SchemaRef>>

Fetches the schema of specified tables in a ClickHouse database.

This method queries ClickHouse to retrieve the Arrow schemas of the specified tables in the given database (or the client’s default database if None). If the tables list is empty, it fetches schemas for all tables in the database. The result is a mapping of table names to their corresponding Arrow SchemaRef.

§Parameters
  • database: Optional database name. If None, uses the client’s default database.
  • tables: A list of table names to fetch schemas for. An empty list fetches all tables.
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result containing a HashMap<String, SchemaRef>, mapping table names to their schemas.

§Errors
  • Fails if the database or any table does not exist or is inaccessible.
  • Fails if the query execution encounters a ClickHouse error (e.g., permission denied).
  • Fails if the connection to ClickHouse is interrupted.
§Examples
use clickhouse_arrow::prelude::*;

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

let schemas = client.fetch_schema(Some("my_db"), &["my_table"], None)
    .await
    .unwrap();
for (table, schema) in schemas {
    println!("Table {} schema: {:?}", table, schema);
}
Source

pub async fn create_table( &self, database: Option<&str>, table: &str, schema: &SchemaRef, options: &CreateOptions, qid: Option<Qid>, ) -> Result<()>

Issues a CREATE TABLE DDL statement for a table using Arrow schema.

Creates a table in the specified database (or the client’s default database if None) based on the provided Arrow SchemaRef. The options parameter allows customization of table properties, such as engine type and partitioning. This method is specific to ArrowClient for seamless integration with Arrow-based data pipelines.

§Parameters
  • database: Optional database name. If None, uses the client’s default database.
  • table: Name of the table to create.
  • schema: The Arrow schema defining the table’s structure.
  • options: Configuration for table creation (e.g., engine, partitioning).
  • qid: Optional query ID for tracking and debugging.
§Returns

A Result indicating success or failure of the operation.

§Errors
  • Fails if the provided schema is invalid or incompatible with ClickHouse.
  • Fails if the database does not exist or is inaccessible.
  • Fails if the query execution encounters a ClickHouse error.
§Examples
use clickhouse_arrow::prelude::*;
use arrow::datatypes::{Schema, SchemaRef};

let client = Client::builder()
    .with_endpoint("localhost:9000")
    .build_arrow()
    .await
    .unwrap();

// Assume `schema` is a valid Arrow schema
let schema: SchemaRef = Arc::new(Schema::new(vec![/* ... */]));
let options = CreateOptions::default();
client.create_table(Some("my_db"), "my_table", &schema, &options, None)
    .await
    .unwrap();

Trait Implementations§

Source§

impl<T: Clone + ClientFormat> Clone for Client<T>

Source§

fn clone(&self) -> Client<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug + ClientFormat> Debug for Client<T>

Source§

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

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

impl<T: ClientFormat> Drop for Client<T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Client<T>

§

impl<T> !RefUnwindSafe for Client<T>

§

impl<T> Send for Client<T>

§

impl<T> Sync for Client<T>

§

impl<T> Unpin for Client<T>

§

impl<T> !UnwindSafe for Client<T>

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<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more