Expand description
Asynchronous ClickHouse client for Rust over the native TCP protocol, a maintained continuation of the clickhouse-rs crate: LZ4 and ZSTD, TLS, a connection pool, and Variant, Dynamic and JSON columns.
§clickhouse-native-rs
An async Rust client that talks to ClickHouse over its native TCP protocol, in columnar blocks: the form ClickHouse itself keeps its data in.
This crate is a maintained continuation of the
clickhouse-rs crate by Mikhail Sukharev,
whose last release is 1.1.0-alpha.1 of 2023-09-10. 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. It is maintained by
Alexander Panasenko, who tracks current
ClickHouse releases and keeps the API close to the original, so that moving
over is mostly a rename (what else it takes).
Documentation · Source · Changelog · Issues
§Why clickhouse-native-rs
- Moving from the
clickhouse-rscrate is mostly a rename of the dependency and the paths; see Moving from clickhouse-rs for the rest. - Dynamic and JSON columns in the native format, including the values past
max_typesand the paths pastmax_dynamic_paths, which the server keeps apart from the rest. Also Variant, BFloat16, Time and Time64, the geo types, and 256-bit integers and decimals. See Data types. - Tested in CI against ClickHouse 26.3, 26.8 and 26.11, and over TLS (rustls and native-tls) against 26.11. Older servers are not tested. The client speaks native protocol revision 54492.
- Speed, in the benchmark below: on SELECT about as fast as
clickhouse-arrow and allocating less (48 MiB against 71), and in wall time
about four times faster than the official
clickhousecrate over HTTP and five times faster than klickhouse; on INSERT clickhouse-arrow is a little faster (34-39 ms against 39-42). - Compression: sends LZ4 or ZSTD and reads replies in either.
- A connection pool, with retries and alternative hosts.
- Query parameters bound by the server, never spliced into the text.
- Streaming of rows or whole blocks as a
Stream. - TLS through rustls or native-tls.
§Installation
[dependencies]
clickhouse-native-rs = "2"The library is imported as clickhouse_native_rs:
use clickhouse_native_rs::{Block, Pool};Every merged pull request is released, so new versions come often. The CHANGELOG lists no breaking change after 2.0.0. The crate is tested with the latest stable Rust; no minimum supported version is declared.
§Optional features
tokio_io(enabled by default) — I/O based on Tokio.async_std— I/O based on async-std, instead oftokio_io. It is kept for compatibility: async-std is deprecated upstream, and CI only lints this feature, it does not test it.tls-rustls— TLS with rustls (only withtokio_io).tls-native-tls— TLS with native-tls (only withtokio_io).tls— alias fortls-native-tls.
Pick one TLS feature: the two cannot be enabled together. The documentation on
docs.rs is built with tls-rustls; with tls-native-tls, Certificate also
converts into a native_tls::Certificate.
§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 = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "tcp://localhost:9000?compression=lz4".into());
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(())
}§Data types
A value is read with row.get::<T, _>(column) or block.get::<T, _>(row, column)
as one of these Rust types. A column is inserted from a Vec of them
(Vec<Option<T>> for a Nullable column, Vec<Vec<T>> for an array), or row
by row with the row! macro.
| ClickHouse | Rust |
|---|---|
Bool | bool |
UInt8 … UInt128, Int8 … Int128 | u8 … u128, i8 … i128 |
UInt256, Int256 | types::UInt256, types::Int256 |
Float32, Float64, BFloat16 | f32, f64, types::BFloat16 |
Decimal(P, S), Decimal32 … Decimal256 | types::Decimal up to 38 digits, types::Decimal256 up to 76 |
String, FixedString(N) | String, &str, Vec<u8>, &[u8] |
Date, Date32 | chrono::NaiveDate |
DateTime, DateTime64 | chrono::DateTime<chrono_tz::Tz> |
Time, Time64(N) | chrono::Duration |
IntervalNanosecond … IntervalYear | types::Interval |
IPv4, IPv6 | std::net::Ipv4Addr, std::net::Ipv6Addr |
UUID | uuid::Uuid |
Enum8, Enum16 | types::Enum8, types::Enum16 |
Nullable(T) | Option<T> |
Array(T) | Vec<T> |
Map(K, V) | HashMap<K, V> |
Tuple(T1, T2, …), named tuples | (T1, T2, …) |
LowCardinality(T), SimpleAggregateFunction(F, T) | as T |
Point, Ring, LineString, MultiLineString, Polygon, MultiPolygon | (f64, f64) for a point, Vecs of points for the rest |
Variant(T1, T2, …), Dynamic | Option<T> of the row’s type, None for NULL |
JSON, JSON(…) | types::Value::Json (paths and values), or String (the JSON text) |
| any of them | types::Value |
- Variant is inserted from a column of one of its types (or a Nullable of one), or as it was read.
- Dynamic is inserted from a column of one type (or a Nullable of one), a
Variant, or as it was read. It holds any number of types: the server keeps
those past
max_typesin its shared variant, and the client reads them too. - JSON is inserted from JSON texts, or as it was read. The server keeps the
paths past
max_dynamic_pathsin its shared data, and the client reads them too.
§More examples
§Streaming
stream gives rows and stream_blocks whole blocks as the server sends them,
so a result never has to fit in memory. query_timeout doesn’t limit them.
The StreamExt here is from futures-util.
use clickhouse_native_rs::{errors::Error, ClientHandle};
use futures_util::StreamExt;
async fn sum(client: &mut ClientHandle) -> Result<u64, Error> {
let mut blocks = client
.query("SELECT number FROM system.numbers LIMIT 100000000")
.stream_blocks();
let mut sum = 0;
while let Some(block) = blocks.next().await {
for row in block?.rows() {
let number: u64 = row.get("number")?;
sum += number;
}
}
Ok(sum)
}§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::{errors::Error, types::Query, ClientHandle};
async fn amounts(client: &mut ClientHandle) -> Result<(), Error> {
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?;
println!("{} rows", block.row_count());
Ok(())
}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.
§Dynamic
use clickhouse_native_rs::{errors::Error, types::Value, Block, ClientHandle};
async fn events(client: &mut ClientHandle) -> Result<(), Error> {
client
.execute("CREATE TABLE IF NOT EXISTS events (id UInt32, payload Dynamic) ENGINE = Memory")
.await?;
// Each block goes in as its own type.
let words = Block::new()
.column("id", vec![1_u32, 2])
.column("payload", vec!["login", "logout"]);
client.insert("events", words).await?;
let numbers = Block::new()
.column("id", vec![3_u32, 4])
.column("payload", vec![Some(42_u64), None]);
client.insert("events", numbers).await?;
let block = client
.query("SELECT id, payload FROM events ORDER BY id")
.fetch_all()
.await?;
for row in block.rows() {
let id: u32 = row.get("id")?;
if id <= 2 {
let word: Option<String> = row.get("payload")?;
println!("{id}: {word:?}");
} else {
// Any row as a Value, whatever its type.
let value: Value = row.get("payload")?;
println!("{id}: {value}");
}
}
Ok(())
}§JSON
use clickhouse_native_rs::{errors::Error, types::Value, Block, ClientHandle};
async fn documents(client: &mut ClientHandle) -> Result<(), Error> {
client
.execute("CREATE TABLE IF NOT EXISTS docs (id UInt32, doc JSON) ENGINE = Memory")
.await?;
let block = Block::new()
.column("id", vec![1_u32])
.column("doc", vec![r#"{"user":{"name":"ann"},"tags":["a","b"]}"#.to_string()]);
client.insert("docs", block).await?;
let block = client.query("SELECT doc FROM docs").fetch_all().await?;
for row in block.rows() {
// The JSON text, as the server writes it.
let text: String = row.get("doc")?;
println!("{text}");
// Or each path and its value.
if let Value::Json(paths) = row.get::<Value, _>("doc")? {
for (path, value) in paths.iter() {
println!("{path} = {value}");
}
}
}
Ok(())
}§Connection URL
schema://user:password@host[:port]/database?param1=value1&...¶mN=valueNFor example:
tcp://user:password@host:9000/clicks?compression=lz4&ping_timeout=42ms§Parameters
-
compression- Compression of the data the client sends:none(the default),lz4orzstd. Without it a query’s data crosses the network uncompressed;lz4is the usual choice.With
lz4orzstdthe server compresses its replies too, using the method of itsnetwork_compression_methodsetting (ZSTD by default since ClickHouse 26.11); the client reads both. Addnetwork_compression_method=lz4to the URL to ask for LZ4 replies.zstdcompresses at the level of thenetwork_zstd_compression_levelsetting (network_zstd_compression_level=1in 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 connecting (defaults to500 ms). -
query_timeout- Timeout forQueryResult::fetch_all(defaults to180 sec);streamandstream_blocksare not limited by it. -
insert_timeout- Timeout for inserts (defaults to180 sec). -
execute_timeout- Timeout for execute (defaults to180 sec). -
keepalive- TCP keep alive timeout in milliseconds. -
nodelay- Whether to enableTCP_NODELAY(defaults totrue). -
pool_min- Lower bound of opened connections forPool(defaults to10). -
pool_max- Upper bound of opened connections forPool(defaults to20). -
ping_before_query- Whether to ping the server before every query, insert and execute (defaults totrue). The ping costs one round trip each time;ping_before_query=falseturns it off. -
send_retries- Number of retries of a request that fails to send (defaults to3). -
retry_timeout- Time to wait before the next retry (defaults to5 sec). -
ping_timeout- Timeout for a ping (defaults to500 ms). -
alt_hosts- Comma-separated list of otherhost:portaddresses. The pool opens its connections to the URL’s host and these in turn. -
secure- Use TLS (needs atls-*feature). -
skip_verify- Do not verify the server certificate (needs atls-*feature).
Any other parameter is sent to the server as a query setting, for example
readonly=1 or max_threads=4.
§Moving from clickhouse-rs
Change the dependency to clickhouse-native-rs = "2" (see
Installation) and the paths:
// before
use clickhouse_rs::{Block, Pool};
// after
use clickhouse_native_rs::{Block, Pool};Two things may need more than the rename:
-
Value,ValueRefandSqlTypeare#[non_exhaustive]since 2.0.0, so an exhaustivematchon them needs a_ =>arm. -
Some reads and inserts that returned wrong data or panicked in
clickhouse-rsreturn an error now. These include:- a decimal that does not fit its column;
- a
LowCardinalitycolumn read throughIterableas its dictionary type; - a
Maptype given for a column that is not a map.
The CHANGELOG lists each of them.
§Performance
The same table read and written by four Rust clients:
- clickhouse-native-rs 2.24.0, klickhouse 0.16.0 and clickhouse-arrow 0.2.1 over the native protocol;
- the official
clickhousecrate 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-42 ms, 90 MiB | 35-38 ms, 48 MiB |
| klickhouse | 408-409 ms, 950 MiB | 181-192 ms, 845 MiB |
| clickhouse-arrow | 34-39 ms, 66 MiB | 34-35 ms, 71 MiB |
clickhouse (HTTP) | 47-51 ms, 25 MiB | 157-158 ms, 77-78 MiB |
How it was measured:
- Each cell is the wall time and the bytes allocated in total during the operation (not peak memory), for the median of ten runs; a range covers two benchmark runs.
- Every client inserts into a
Nulltable from data it already holds in its own form: columns, row structs or an Arrow batch. - Every client reads all rows of a
Memorytable into its own form. This crate gives a columnar block, clickhouse-arrow Arrow batches, and theclickhousecrate and klickhouse row structs (klickhouse is measured through itsRowAPI only). What a program does with the data afterwards is not measured. - 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. One server and one client, so take the numbers as this setup’s, not as a general ranking.
- Measured on 2026-11-28 with the code of 2.24.0. The raw output of both runs is in benches/compare/results/2026-11-28.md.
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 --lockedbenches/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§Authors
- Alexander Panasenko (@alex09x, alex@prod.codes) maintains this crate.
- Mikhail Sukharev wrote clickhouse-rs, which it continues.
To cite the crate, see CITATION.cff.
§License
MIT, see LICENSE.
Re-exports§
pub use crate::errors::ConnectionError;pub use crate::pool::Pool;pub use crate::types::block::Block;pub use crate::types::Compression;pub use crate::types::Options;pub use crate::types::Simple;
Modules§
Macros§
Structs§
- Block
- Represents Clickhouse Block
- Client
Handle - Clickhouse client handle.