Databases
Validate rows before Insert::write and after fetch_all with the clickhouse crate.

vld_data::clickhouse validates rows of the official clickhouse client against vld schemas: before they are written to an INSERT and after a SELECT is fetched.

Install

Cargo.toml
[dependencies]
vld = "0.8"
vld-data = { version = "0.8", features = ["clickhouse"] }
clickhouse = "0.15"
FeatureModuleNotes
clickhousevld_data::clickhouseclickhouse 0.15, needs Rust 1.89; vld-data enables none of its features

Example

use vld_data::clickhouse::prelude::*;

vld::schema! {
    #[derive(Debug)]
    pub struct EventSchema {
        pub name: String => vld::string().min(1),
        pub value: i64 => vld::number().int().min(0),
    }
}

#[derive(clickhouse::Row, serde::Serialize, serde::Deserialize)]
struct Event { name: String, value: i64 }

async fn run(client: clickhouse::Client) -> Result<(), VldClickhouseError> {
    let mut insert = client.insert::<Event>("events").await?;
    insert_validated::<EventSchema, _>(&mut insert, &Event { name: "click".into(), value: 1 }).await?;
    insert.end().await?;

    let rows: Vec<Event> =
        fetch_all_validated::<EventSchema, _>(client.query("SELECT ?fields FROM events")).await?;
    Ok(())
}

API

  • insert_validated::<S, T>(&mut insert, &row) — validate, then Insert::write.
  • fetch_all_validated::<S, T>(query) — Query::fetch_all, then validate every row.
  • validate_row::<S, T>(&row), validate_rows::<S, T>(&[row]) — the check alone (the batch returns the first bad index).
  • VldClickhouseError — Validation, Serialization, InvalidRow { index, error } (from fetch_all_validated), Clickhouse(clickhouse::error::Error).

Gotchas

  • Rows are validated through serde_json (serde::Serialize of the row), not through RowBinary: a field with a custom #[serde(with = "clickhouse::serde::...")] is seen as that serializer writes it to JSON.
  • An invalid row is not written, and the INSERT stays usable for the next rows.
  • Row types must be owned (RowOwned), as fetch_all requires.