Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

clickhouse-rs

> 数据库
Open source

Official pure Rust typed client for ClickHouse DB

547 stars0 likes1 views
WebsiteGitHub

About

Official pure Rust typed client for ClickHouse DB

clickhouse-rs

Official pure Rust typed client for ClickHouse DB.

Crates.io Documentation Build Status License Codecov

  • Uses serde for encoding/decoding rows.
  • Supports serde attributes: skip_serializing, skip_deserializing, rename.
  • Uses RowBinaryWithNamesAndTypes or RowBinary formats over HTTP transport.
    • By default, RowBinaryWithNamesAndTypes with database schema validation is used.
    • It is possible to switch to RowBinary, which can potentially lead to increased performance (see below).
    • There are plans to implement Native format over TCP.
  • Supports TLS (see native-tls and rustls-tls features below).
  • Supports compression and decompression (LZ4, LZ4HC, and ZSTD).
  • Provides API for selecting.
  • Provides API for inserting.
  • Provides API for infinite transactional (see below) inserting.
  • Provides mocks for unit testing.

Note: ch2rs is useful to generate a row type from ClickHouse.

Validation

Starting from 0.14.0, the crate uses RowBinaryWithNamesAndTypes format by default, which allows row types validation against the ClickHouse schema. This enables clearer error messages in case of schema mismatch at the cost of performance. Additionally, with enabled validation, the crate supports structs with correct field names and matching types, but incorrect order of the fields, with an additional slight (5-10%) performance penalty.

If you are looking to maximize performance, you could disable validation using Client::with_validation(false). When validation is disabled, the client switches to RowBinary format usage instead.

The downside with plain RowBinary is that instead of clearer error messages, a mismatch between Row and database schema will result in a NotEnoughData error without specific details.

However, depending on the dataset, there might be x1.1 to x3 performance improvement, but that highly depends on the shape and volume of the dataset.

It is always recommended to measure the performance impact of validation in your specific use case. Additionally, writing smoke tests to ensure that the row types match the ClickHouse schema is highly recommended, if you plan to disable validation in your application.

Usage

To use the crate, add this to your Cargo.toml:

toml
[dependencies]
clickhouse = "0.14.2"

[dev-dependencies]
clickhouse = { version = "0.14.2", features = ["test-util"] }

Create a client

use clickhouse::Client;

let client = Client::default()
    .with_url("http://localhost:8123")
    .with_user("name")
    .with_password("123")
    .with_database("test");
  • Reuse created clients or clone them in order to reuse a connection pool.

Select rows

use serde::Deserialize;
use clickhouse::Row;

#[derive(Row, Deserialize)]
struct MyRow {
    no: u32,
    name: &'a str,
}

async fn example(client: clickhouse::Client) -> clickhouse::error::Result {
    let mut cursor = client
        .query("SELECT ?fields FROM some WHERE no BETWEEN ? AND ?")
        .bind(500)
        .bind(504)
        .fetch::>()?;

    while let Some(row) = cursor.next().await? {
        println!("no: {}, name: {}", row.no, row.name);
    }
    
    Ok(())
}
  • Placeholder ?fields is replaced with no, name (fields of Row).
  • Placeholder ? is replaced with values in following bind() calls.
  • Convenient fetch_one::() and fetch_all::() can be used to get a first row or all rows correspondingly.
  • sql::Identifier can be used to bind table names.
  • Use client.query_raw(..) to send SQL to the server as-is, without any placeholder parsing: ? is not treated as a placeholder, ?? is not unescaped, and ?fields is not substituted. To parameterize such queries, use server-side parameters ({name: type}) via .param(..).

Note that cursors can return an error even after producing some rows. To avoid this, use client.with_setting("wait_end_of_query", "1") in order to enable buffering on the server-side. More details. The buffer_size setting can be useful too.

Insert a batch

use serde::Serialize;
use clickhouse::Row;

#[derive(Row, Serialize)]
struct MyRow {
    no: u32,
    name: String,
}

async fn example(client: clickhouse::Client) -> clickhouse::error::Result {
    let mut insert = client.insert::("some").await?;
    insert.write(&MyRow { no: 0, name: "foo".into() }).await?;
    insert.write(&MyRow { no: 1, name: "bar".into() }).await?;
    insert.end().await?;
    Ok(())
}
  • If end() isn't called, the INSERT is aborted.
  • Rows are being sent progressively to spread network load.
  • ClickHouse inserts batches atomically only if all rows fit in the same partition and their number is less max_insert_block_size.

Infinite inserting

Requires the inserter feature.

…

Please, read examples to understand how to use it properly in different real-world cases.

  • Inserter ends an active insert in commit() if thresholds (max_bytes, max_rows, period) are reached.
  • The interval between ending active INSERTs can be biased by using with_period_bias to avoid load spikes by parallel inserters.
  • Inserter::time_left() can be used to detect when the current period ends. Call Inserter::commit() again to check limits if your stream emits items rarely.
  • Time thresholds implemented by using quanta crate to speed the inserter up. Not used if test-util is enabled (thus, time can be managed by tokio::time::advance() in custom tests).
  • All rows between commit() calls are inserted in the same INSERT statement.
  • Do not forget to flush if you want to terminate inserting:
inserter.end().await?;

Perform DDL

async fn example(client: clickhouse::Client) -> clickhouse::error::Result {
    client.query("DROP TABLE IF EXISTS some").execute().await?;
    Ok(())
}

Feature Flags

  • lz4 (enabled by default) — enables Compression::Lz4. If enabled, Compression::Lz4 is used by default for all queries.
  • zstd — enables Compression::Zstd(level). If enabled and lz4 is not, Compression::zstd() is used by default for all queries. Uses enable_http_compression for responses instead of native framing.
  • inserter — enables client.inserter().
  • test-util — adds mocks. See the example. Use it only in dev-dependencies.
  • uuid — adds serde::uuid to work with uuid crate.
  • time — adds serde::time to work with time crate.
  • chrono — adds serde::chrono to work with chrono crate.
  • opentelemetry — propagate OpenTelemetry context to ClickHouse server.

TLS

By default, TLS is disabled and one or more following features must be enabled to use HTTPS urls:

  • native-tls — uses native-tls, utilizing dynamic linking (e.g. against OpenSSL).
  • rustls-tls — enables rustls-tls-aws-lc and rustls-tls-webpki-roots features.
  • rustls-tls-aws-lc — uses rustls with the aws-lc cryptography implementation.
  • rustls-tls-ring — uses rustls with the ring cryptography implementation.
  • rustls-tls-webpki-roots — uses rustls with certificates provided by the webpki-roots crate.
  • rustls-tls-native-roots — uses rustls with certificates provided by the rustls-native-certs crate.

If multiple features are enabled, the following priority is applied:

  • native-tls > rustls-tls-aws-lc > rustls-tls-ring
  • rustls-tls-native-roots > rustls-tls-webpki-roots

How to choose between all these features? Here are some considerations:

  • A good starting point is rustls-tls, e.g. if you use ClickHouse Cloud.
  • To be more environment-agnostic, prefer rustls-tls over native-tls.
  • Enable rustls-tls-native-roots or native-tls if you want to use self-signed certificates.

Data Types

Usage of all mentioned data types are covered in the following examples:

  • Simple ClickHouse data types
  • Container-like ClickHouse data types
  • Variant data type
  • JSON data type

Overview

  • (U)Int(8|16|32|64|128) maps to/from corresponding (u|i)(8|16|32|64|128) types or newtypes around them.

  • (U)Int256 are supported with convenience wrappers over [u8; 32]: clickhouse::types::Int256 and clickhouse::types::UInt256. See the derive example.

  • Float(32|64) maps to/from corresponding f(32|64) or newtypes around them.

  • Decimal(32|64|128) maps to/from corresponding i(32|64|128) or newtypes around them. It's more convenient to use fixnum or another implementation of signed fixed-point numbers.

  • Boolean maps to/from bool or newtypes around it.

  • String maps to/from any string or bytes types, e.g. &str, &[u8], String, Vec or SmartString. Newtypes are also supported. To store bytes, consider using serde_bytes, because it's more efficient.

    Example

    use serde::{Serialize, Deserialize};
    use clickhouse::Row;
    
    #[derive(Row, Debug, Serialize, Deserialize)]
    struct MyRow {
        str: &'a str,
        string: String,
        #[serde(with = "serde_bytes")]
        bytes: Vec,
        #[serde(with = "serde_bytes")]
        byte_slice: &'a [u8],
    }
  • FixedString(N) is supported as an array of bytes, e.g. [u8; N].

    Example

    use clickhouse::Row;
    use serde::{Serialize, Deserialize};
    #[derive(Row, Debug, Serialize, Deserialize)]
    struct MyRow {
        fixed_str: [u8; 16], // FixedString(16)
    }
  • Enum(8|16) are supported using serde_repr. You could use #[repr(i8)] for Enum8 and #[repr(i16)] for Enum16.

    Example

    use clickhouse::Row;
    use serde::{Serialize, Deserialize};
    use serde_repr::{Deserialize_repr, Serialize_repr};
    
    #[derive(Row, Serialize, Deserialize)]
    struct MyRow {
        level: Level,
    }
    
    #[derive(Debug, Serialize_repr, Deserialize_repr)]
    #[repr(i8)]
    enum Level {
        Debug = 1,
        Info

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rustclickhousehttpruststreaming

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库