docs.rs failed to build clickhouse-native-rs-2.2.0
Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
Visit the last successful build: clickhouse-native-rs-2.24.1

clickhouse-native-rs

Asynchronous ClickHouse client for Rust over the native TCP protocol.

This crate continues clickhouse-rs by Mikhail Sukharev, which has not had a release since 2023. Many thanks to Mikhail and to everyone who contributed to the original project: the code base, the API and most of the type support come from there. We keep it maintained, track current ClickHouse releases and keep the API close to the original so that moving over is a rename.

Installation

[dependencies]
clickhouse-native-rs = "2"

The library is imported as clickhouse_native_rs:

use clickhouse_native_rs::{Block, Pool};

Moving from clickhouse-rs

Change the dependency and the paths; nothing else is required.

[dependencies]
clickhouse-native-rs = "2"
// before
use clickhouse_rs::{Block, Pool};
// after
use clickhouse_native_rs::{Block, Pool};

Supported data types

  • Bool
  • UInt8, UInt16, UInt32, UInt64, UInt128, UInt256, Int8, Int16, Int32, Int64, Int128, Int256
  • Float32, Float64
  • Decimal(P, S) with P up to 38 (Decimal32, Decimal64, Decimal128)
  • String, FixedString(N)
  • Date, DateTime, DateTime64
  • IPv4, IPv6, UUID
  • Enum8, Enum16
  • Nullable(T), Array(T), LowCardinality(T), Map(K, V), Tuple(T1, T2, ...) and named tuples
  • Point, Ring, LineString, MultiLineString, Polygon, MultiPolygon, MultiPoint, read as their tuple and array forms: Tuple(Float64, Float64) for a point
  • SimpleAggregateFunction(F, T)

Connection URL

schema://user:password@host[:port]/database?param1=value1&...&paramN=valueN

parameters:

  • compression - Compression of the data the client sends (defaults to none). Possible choices:

    • none
    • lz4
    • zstd

    With lz4 or zstd the server compresses its replies too, using the method of its network_compression_method setting (ZSTD by default since ClickHouse 26.11); the client reads both. Add network_compression_method=lz4 to the URL to ask for LZ4 replies.

    zstd compresses at the level of the network_zstd_compression_level setting (network_zstd_compression_level=1 in the URL) when it is an integer from 1 to 22, and at 3, the server default since ClickHouse 26.9, otherwise. The setting itself is sent to the server unchanged.

  • connection_timeout - Timeout for connection (defaults to 500 ms)

  • query_timeout - Timeout for QueryResult::fetch_all (defaults to 180 sec); stream and stream_blocks are not limited by it.

  • insert_timeout - Timeout for inserts (defaults to 180 sec).

  • execute_timeout - Timeout for execute (defaults to 180 sec).

  • keepalive - TCP keep alive timeout in milliseconds.

  • nodelay - Whether to enable TCP_NODELAY (defaults to true).

  • pool_min - Lower bound of opened connections for Pool (defaults to 10).

  • pool_max - Upper bound of opened connections for Pool (defaults to 20).

  • ping_before_query - Ping server every time before execute any query. (defaults to true).

  • send_retries - Count of retry to send request to server. (defaults to 3).

  • retry_timeout - Amount of time to wait before next retry. (defaults to 5 sec).

  • ping_timeout - Timeout for ping (defaults to 500 ms).

  • alt_hosts - Comma separated list of single address host for load-balancing.

  • secure - Use TLS (needs a tls-* feature).

  • skip_verify - Do not verify the server certificate (needs a tls-* feature).

Any other parameter is sent to the server as a query setting, for example readonly=1 or max_threads=4.

example:

tcp://user:password@host:9000/clicks?compression=lz4&ping_timeout=42ms

Optional features

Some functionality sits behind optional features to keep compile time down for the most common use cases. The following features are available.

  • tokio_io (enabled by default) — I/O based on Tokio.
  • async_std — I/O based on async-std (doesn't work together with tokio_io).
  • tls-native-tls — TLS support with native-tls (allowed only with tokio_io).
  • tls-rustls — TLS support with rustls (allowed only with tokio_io).
  • tls — alias for tls-native-tls.

Example

use clickhouse_native_rs::{Block, Pool};
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let ddl = r"
        CREATE TABLE IF NOT EXISTS payment (
            customer_id  UInt32,
            amount       UInt32,
            account_name Nullable(FixedString(3))
        ) Engine=Memory";

    let block = Block::new()
        .column("customer_id",  vec![1_u32,  3,  5,  7,  9])
        .column("amount",       vec![2_u32,  4,  6,  8, 10])
        .column("account_name", vec![Some("foo"), None, None, None, Some("bar")]);

    let database_url = "tcp://localhost:9000?compression=lz4";
    let pool = Pool::new(database_url);

    let mut client = pool.get_handle().await?;
    client.execute(ddl).await?;
    client.insert("payment", block).await?;
    let block = client.query("SELECT * FROM payment").fetch_all().await?;

    for row in block.rows() {
        let id: u32             = row.get("customer_id")?;
        let amount: u32         = row.get("amount")?;
        let name: Option<&str>  = row.get("account_name")?;
        println!("Found payment {}: {} {:?}", id, amount, name);
    }

    Ok(())
}

Running the tests

The integration tests need a ClickHouse server. Start one with docker compose up -d; the tests connect to localhost:9000 unless DATABASE_URL says otherwise:

DATABASE_URL="tcp://localhost:9000?compression=lz4" mitts test

License

MIT, see LICENSE.