clickhouse-native-rs 2.23.0

Asynchronous ClickHouse client for Rust over the native TCP protocol.
Documentation

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, BFloat16
  • Decimal(P, S) with P up to 76 (Decimal32, Decimal64, Decimal128, Decimal256; from 39 digits on, values are types::Decimal256)
  • String, FixedString(N)
  • Date, Date32, DateTime, DateTime64, Time, Time64(N)
  • IntervalNanosecond … IntervalYear
  • 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)
  • Variant(T1, T2, ...): a value of one of the types or NULL, read as an Option of the row's type; inserted from a column of one of the types (or a Nullable of one), or as read
  • Dynamic, Dynamic(max_types=N): a value of any type or NULL, read as an Option of the row's type; inserted from a column of one type (or a Nullable of one), a Variant, or as read; also the values past the limit of types (the server's shared variant)
  • JSON, JSON(...): an object of paths and values, read as Value::Json or as JSON text into a String; inserted from JSON texts, or as read; also the paths past the limit of dynamic paths (the server's shared data)

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

Query parameters

Values for {name:Type} placeholders go with the query, never spliced into its text; the server parses each one as Type:

use clickhouse_native_rs::types::Query;

let query = Query::new("SELECT amount FROM payment WHERE customer_id = {id:UInt32} AND account_name = {name:String}")
    .param("id", 5_u32)
    .param("name", "it's");
let block = client.query(query).fetch_all().await?;

Numbers, strings, dates and times, UUIDs, IP addresses, decimals, enums, Option (NULL), arrays, maps and tuples can be bound, as Values or what converts into one. execute takes such a query too.

Performance

The same table read and written by four Rust clients:

  • clickhouse-native-rs 2.18.0, klickhouse 0.16.0 and clickhouse-arrow 0.2.1 over the native protocol;
  • clickhouse 0.15.3 over HTTP.

The table has 500,000 rows of eight columns: Int32, String (500 distinct symbols), Date, Int32, Int32, Int64, Int64, Int32.

client INSERT SELECT
clickhouse-native-rs 39-40 ms, 90 MiB 49 ms, 111 MiB
klickhouse 403-405 ms, 950 MiB 179-235 ms, 845 MiB
clickhouse-arrow 36-43 ms, 66 MiB 36-37 ms, 71 MiB
clickhouse (HTTP) 46-47 ms, 25 MiB 158-159 ms, 79 MiB

How it was measured:

  • Each cell is the wall time and the bytes the client allocated, for the median of ten runs; a range covers two benchmark runs.
  • Every client inserts into a Null table from data it already holds in its own form: columns, row structs or an Arrow batch.
  • Every client reads all rows of a Memory table into its own form: a block, row structs or Arrow batches.
  • All four compress with LZ4, the server too, and insert synchronously (async_insert = 0).
  • Server: ClickHouse 26.11.4 on an AMD Ryzen 9 7950X. Client: an AMD Ryzen 9 7950X3D on the same LAN.

The harness is benches/compare. It is not part of the library's build, and its Cargo.lock holds the dependency graph measured:

cd benches/compare
NATIVE=host:9000 HTTP=http://host:8123 mitts run --release --locked

benches/trades.rs measures this client alone, also without compression:

DATABASE_URL="tcp://host:9000?compression=lz4" mitts bench --bench trades

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.