clickhouse-native-rs 2.24.1

Asynchronous ClickHouse client for Rust over the native TCP protocol, a maintained continuation of the clickhouse-rs crate.
Documentation
/*
 * clickhouse-native-rs — Asynchronous ClickHouse client for Rust over the native TCP protocol
 * Copyright (c) 2026 Alexander Panasenko
 *
 * Contact: alex@prod.codes
 * Author: https://prod.codes/about/
 * Project: https://github.com/alex09x/clickhouse-native-rs
 * SPDX-License-Identifier: MIT
 */

//! The text of a JSON value: its paths (`a.b`) nested as objects, numbers
//! and booleans as they are, NULL as `null`, arrays and tuples as arrays, and
//! the other values (dates, times, UUIDs, addresses, enums) as the strings
//! the client shows them as.

use std::fmt::Write as _;

use chrono::TimeZone;
use chrono_tz::Tz;
use either::Either;

use super::ValueRef;

/// The JSON object of `paths`, in the order of the paths.
pub(crate) fn object_text(paths: &[(&str, ValueRef<'_>)]) -> String {
    let mut text = String::new();
    let entries: Vec<(&str, &ValueRef<'_>)> =
        paths.iter().map(|(path, value)| (*path, value)).collect();
    object(&mut text, &entries);
    text
}

/// An object of `entries` in the order of their paths: those with the same
/// first part before a dot are one object under it.
fn object(text: &mut String, entries: &[(&str, &ValueRef<'_>)]) {
    let mut entries = entries.to_vec();
    entries.sort_by(|a, b| a.0.cmp(b.0));
    text.push('{');
    let mut index = 0;
    while index < entries.len() {
        if index > 0 {
            text.push(',');
        }
        let (path, value) = entries[index];
        match path.split_once('.') {
            None => {
                string(text, path);
                text.push(':');
                json(text, value);
                index += 1;
            }
            Some((head, _)) => {
                let mut inner = Vec::new();
                while let Some((rest, value)) = entries.get(index).and_then(|(path, value)| {
                    let (first, rest) = path.split_once('.')?;
                    (first == head).then_some((rest, *value))
                }) {
                    inner.push((rest, value));
                    index += 1;
                }
                string(text, head);
                text.push(':');
                object(text, &inner);
            }
        }
    }
    text.push('}');
}

fn json(text: &mut String, value: &ValueRef<'_>) {
    match value {
        ValueRef::Nullable(Either::Left(_)) => text.push_str("null"),
        ValueRef::Nullable(Either::Right(value)) => json(text, value),
        ValueRef::Bool(b) => text.push_str(if *b { "true" } else { "false" }),
        ValueRef::UInt8(_)
        | ValueRef::UInt16(_)
        | ValueRef::UInt32(_)
        | ValueRef::UInt64(_)
        | ValueRef::UInt128(_)
        | ValueRef::UInt256(_)
        | ValueRef::Int8(_)
        | ValueRef::Int16(_)
        | ValueRef::Int32(_)
        | ValueRef::Int64(_)
        | ValueRef::Int128(_)
        | ValueRef::Int256(_)
        | ValueRef::Decimal(_)
        | ValueRef::Decimal256(..) => {
            let _ = write!(text, "{value}");
        }
        ValueRef::Float32(f) => number(text, f64::from(*f)),
        ValueRef::Float64(f) => number(text, *f),
        ValueRef::BFloat16(f) => number(text, f64::from(f32::from(*f))),
        ValueRef::String(bytes) => string(text, &String::from_utf8_lossy(bytes)),
        // As the server writes them: in their zone, with the digits of their
        // precision.
        ValueRef::DateTime(seconds, tz) => string(text, &time(i64::from(*seconds), 0, 0, *tz)),
        ValueRef::DateTime64(value, (precision, tz)) => {
            let scale = 10_i64.checked_pow(*precision).unwrap_or(1);
            let seconds = value.div_euclid(scale);
            let fraction = value.rem_euclid(scale);
            string(text, &time(seconds, fraction, *precision, *tz));
        }
        ValueRef::Array(_, values) | ValueRef::Tuple(values) => {
            text.push('[');
            for (index, value) in values.iter().enumerate() {
                if index > 0 {
                    text.push(',');
                }
                json(text, value);
            }
            text.push(']');
        }
        ValueRef::Map(_, _, entries) => {
            let mut entries: Vec<(String, &ValueRef<'_>)> = entries
                .iter()
                .map(|(key, value)| (key_text(key), value))
                .collect();
            entries.sort_by(|a, b| a.0.cmp(&b.0));
            text.push('{');
            for (index, (key, value)) in entries.into_iter().enumerate() {
                if index > 0 {
                    text.push(',');
                }
                string(text, &key);
                text.push(':');
                json(text, value);
            }
            text.push('}');
        }
        ValueRef::Json(paths) => {
            let entries: Vec<(&str, &ValueRef<'_>)> =
                paths.iter().map(|(path, value)| (*path, value)).collect();
            object(text, &entries);
        }
        value => string(text, &value.to_string()),
    }
}

fn key_text(key: &ValueRef<'_>) -> String {
    match key {
        ValueRef::String(bytes) => String::from_utf8_lossy(bytes).into_owned(),
        key => key.to_string(),
    }
}

/// `YYYY-MM-DD hh:mm:ss` in `tz`, with `precision` digits of `fraction`.
fn time(seconds: i64, fraction: i64, precision: u32, tz: Tz) -> String {
    let Some(time) = tz.timestamp_opt(seconds, 0).single() else {
        return seconds.to_string();
    };
    let mut text = time.format("%Y-%m-%d %H:%M:%S").to_string();
    if precision > 0 {
        let _ = write!(text, ".{fraction:0width$}", width = precision as usize);
    }
    text
}

/// A finite number as it is; NaN and the infinities have no JSON form.
fn number(text: &mut String, value: f64) {
    if value.is_finite() {
        let _ = write!(text, "{value}");
    } else {
        text.push_str("null");
    }
}

fn string(text: &mut String, value: &str) {
    text.push('"');
    for c in value.chars() {
        match c {
            '"' => text.push_str("\\\""),
            '\\' => text.push_str("\\\\"),
            '\n' => text.push_str("\\n"),
            '\r' => text.push_str("\\r"),
            '\t' => text.push_str("\\t"),
            '\x08' => text.push_str("\\b"),
            '\x0c' => text.push_str("\\f"),
            c if u32::from(c) < 0x20 => {
                let _ = write!(text, "\\u{:04x}", u32::from(c));
            }
            c => text.push(c),
        }
    }
    text.push('"');
}

#[cfg(test)]
mod test {
    use std::sync::Arc;

    use super::*;
    use crate::types::SqlType;

    #[test]
    fn test_object_text() {
        let array = ValueRef::Array(
            &SqlType::Int64,
            Arc::new(vec![ValueRef::Int64(1), ValueRef::Int64(-2)]),
        );
        let inner = ValueRef::Json(Arc::new(vec![("x", ValueRef::Float64(0.5))]));
        let paths = [
            ("a", ValueRef::UInt64(1)),
            ("b.c", ValueRef::String(b"q\"\n\x01")),
            ("b.d", array),
            ("b.e", ValueRef::Nullable(Either::Left(&SqlType::String))),
            ("f", ValueRef::Float64(f64::NAN)),
            ("g", ValueRef::Bool(true)),
            (
                "h",
                ValueRef::Array(&SqlType::String, Arc::new(vec![inner])),
            ),
            ("i", ValueRef::Date(1)),
            ("j", ValueRef::DateTime(36_000, Tz::UTC)),
            ("k", ValueRef::DateTime64(1_500, &(3, Tz::UTC))),
        ];
        assert_eq!(
            object_text(&paths),
            r#"{"a":1,"b":{"c":"q\"\n\u0001","d":[1,-2],"e":null},"f":null,"g":true,"h":[{"x":0.5}],"i":"1970-01-02","j":"1970-01-01 10:00:00","k":"1970-01-01 00:00:01.500"}"#
        );
        assert_eq!(object_text(&[]), "{}");
    }
}