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
 */

//! Query parameters: the values of `{name:Type}` placeholders, which the
//! server fills in. A value travels as text that the server parses for the
//! placeholder's type (`ReplaceQueryParameterVisitor`): the escaped text of
//! TabSeparated, with the elements of arrays, maps and tuples in their quoted
//! form, as in `['a', 'b']`.

use std::io::Write;

use either::Either;

use crate::types::{Value, ValueRef};

/// The text of `value` as a query parameter.
pub(crate) fn param_text(value: &Value) -> Vec<u8> {
    let mut out = Vec::new();
    write_value(value, &mut out, false);
    out
}

/// A parameter's text as the Query packet carries it: a quoted string, which
/// the server unquotes (`readQueryParameters`).
pub(crate) fn quote(text: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(text.len() + 2);
    write_string(text, &mut out, true);
    out
}

fn write_value(value: &Value, out: &mut Vec<u8>, quoted: bool) {
    // Writing into a vector does not fail.
    let _ = match value {
        Value::String(bytes) => {
            write_string(bytes, out, quoted);
            Ok(())
        }
        Value::Float32(v) => write_float(f64::from(*v), &v.to_string(), out),
        Value::Float64(v) => write_float(*v, &v.to_string(), out),
        Value::BFloat16(v) => {
            let v = f32::from(*v);
            write_float(f64::from(v), &v.to_string(), out)
        }
        // Instants as seconds since the epoch, whatever the time zones.
        Value::DateTime(seconds, _) => write!(out, "{seconds}"),
        Value::DateTime64(ticks, (precision, _)) => write_ticks(*ticks, *precision, out),
        Value::ChronoDateTime(time) => {
            write_instant(time.timestamp(), time.timestamp_subsec_nanos(), out)
        }
        Value::Nullable(Either::Left(_)) => out.write_all(if quoted { b"NULL" } else { b"\\N" }),
        Value::Nullable(Either::Right(inner)) => {
            write_value(inner, out, quoted);
            Ok(())
        }
        Value::Array(_, values) => write_all(b'[', values.iter(), b']', out),
        Value::Tuple(values) => write_all(b'(', values.iter(), b')', out),
        Value::Json(_) => {
            let text = ValueRef::from(value).to_string();
            write_string(text.as_bytes(), out, quoted);
            Ok(())
        }
        Value::Map(_, _, entries) => {
            out.push(b'{');
            for (index, (key, value)) in entries.iter().enumerate() {
                if index > 0 {
                    out.push(b',');
                }
                write_value(key, out, true);
                out.push(b':');
                write_value(value, out, true);
            }
            out.push(b'}');
            Ok(())
        }
        Value::Enum8(items, v) => write_enum(
            items.iter().map(|(n, i)| (n, i64::from(*i))),
            v.internal().into(),
            out,
            quoted,
        ),
        Value::Enum16(items, v) => write_enum(
            items.iter().map(|(n, i)| (n, i64::from(*i))),
            v.internal().into(),
            out,
            quoted,
        ),
        // Text in quotes when inside an array, map or tuple.
        Value::Date(_)
        | Value::Date32(_)
        | Value::Time(_)
        | Value::Time64(..)
        | Value::Ipv4(_)
        | Value::Ipv6(_)
        | Value::Uuid(_) => {
            let text = value.to_string();
            write_string(text.as_bytes(), out, quoted);
            Ok(())
        }
        Value::Bool(_)
        | Value::UInt8(_)
        | Value::UInt16(_)
        | Value::UInt32(_)
        | Value::UInt64(_)
        | Value::UInt128(_)
        | Value::UInt256(_)
        | Value::Int8(_)
        | Value::Int16(_)
        | Value::Int32(_)
        | Value::Int64(_)
        | Value::Int128(_)
        | Value::Int256(_)
        | Value::Decimal(_)
        | Value::Decimal256(_)
        | Value::Interval(..) => write!(out, "{value}"),
    };
}

fn write_all<'a>(
    open: u8,
    values: impl Iterator<Item = &'a Value>,
    close: u8,
    out: &mut Vec<u8>,
) -> std::io::Result<()> {
    out.push(open);
    for (index, value) in values.enumerate() {
        if index > 0 {
            out.push(b',');
        }
        write_value(value, out, true);
    }
    out.push(close);
    Ok(())
}

/// `nan`, `inf` and `-inf` as the server reads them; other floats in Rust's
/// shortest exact text, which has no exponent.
fn write_float(value: f64, text: &str, out: &mut Vec<u8>) -> std::io::Result<()> {
    if value.is_nan() {
        out.write_all(b"nan")
    } else if value.is_infinite() {
        out.write_all(if value > 0.0 { b"inf" } else { b"-inf" })
    } else {
        out.write_all(text.as_bytes())
    }
}

/// `seconds[.nanoseconds]` of the instant `nanos` after the second `seconds`
/// (as chrono counts: the second before, for an instant before the epoch).
fn write_instant(seconds: i64, nanos: u32, out: &mut Vec<u8>) -> std::io::Result<()> {
    // A leap second counts more than a billion nanoseconds into its second.
    let (seconds, nanos) = match nanos.checked_sub(1_000_000_000) {
        Some(nanos) => (seconds.saturating_add(1), nanos),
        None => (seconds, nanos),
    };
    match (seconds, nanos) {
        (_, 0) => write!(out, "{seconds}"),
        (0.., _) => write!(out, "{seconds}.{nanos:09}"),
        // -2 s and 0.5 s are -1.5 s.
        _ => write!(
            out,
            "-{}.{:09}",
            seconds.unsigned_abs() - 1,
            1_000_000_000 - nanos
        ),
    }
}

/// `seconds.fraction` of `ticks` with `precision` fraction digits.
fn write_ticks(ticks: i64, precision: u32, out: &mut Vec<u8>) -> std::io::Result<()> {
    let Some(factor) = 10_u64.checked_pow(precision) else {
        return write!(out, "{ticks}");
    };
    let sign = if ticks < 0 { "-" } else { "" };
    let magnitude = ticks.unsigned_abs();
    match precision {
        0 => write!(out, "{ticks}"),
        _ => write!(
            out,
            "{sign}{}.{:0width$}",
            magnitude / factor,
            magnitude % factor,
            width = precision as usize
        ),
    }
}

/// The name of an enum value, or its number when the name is not known.
fn write_enum<'a>(
    mut items: impl Iterator<Item = (&'a String, i64)>,
    value: i64,
    out: &mut Vec<u8>,
    quoted: bool,
) -> std::io::Result<()> {
    match items.find(|(_, number)| *number == value) {
        Some((name, _)) => {
            write_string(name.as_bytes(), out, quoted);
            Ok(())
        }
        None => write!(out, "{value}"),
    }
}

/// A string escaped as TabSeparated has it, in quotes when `quoted`.
fn write_string(bytes: &[u8], out: &mut Vec<u8>, quoted: bool) {
    if quoted {
        out.push(b'\'');
    }
    for &byte in bytes {
        match byte {
            b'\\' => out.extend_from_slice(b"\\\\"),
            b'\t' => out.extend_from_slice(b"\\t"),
            b'\n' => out.extend_from_slice(b"\\n"),
            b'\r' => out.extend_from_slice(b"\\r"),
            0 => out.extend_from_slice(b"\\0"),
            8 => out.extend_from_slice(b"\\b"),
            12 => out.extend_from_slice(b"\\f"),
            b'\'' if quoted => out.extend_from_slice(b"\\'"),
            _ => out.push(byte),
        }
    }
    if quoted {
        out.push(b'\'');
    }
}

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

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

    fn text(value: impl Into<Value>) -> String {
        String::from_utf8(param_text(&value.into())).unwrap()
    }

    #[test]
    fn test_param_text() {
        assert_eq!(text(42_u32), "42");
        assert_eq!(text(-1.5_f64), "-1.5");
        assert_eq!(text(f64::NAN), "nan");
        assert_eq!(text(f32::NEG_INFINITY), "-inf");
        assert_eq!(text("a\tb\\c'd"), "a\\tb\\\\c'd");
        assert_eq!(
            text(vec!["x'y".to_string(), "z".to_string()]),
            "['x\\'y','z']"
        );
        assert_eq!(text(Some(7_u8)), "7");
        assert_eq!(text(None::<u8>), "\\N");
        let nullable = SqlType::Nullable(SqlType::UInt8.into()).into();
        let values = vec![Value::from(Some(1_u8)), Value::from(None::<u8>)];
        assert_eq!(text(Value::Array(nullable, Arc::new(values))), "[1,NULL]");
        assert_eq!(
            String::from_utf8(quote(b"it's \\ a\tb")).unwrap(),
            "'it\\'s \\\\ a\\tb'"
        );
        let mut out = Vec::new();
        write_ticks(-1_500, 3, &mut out).unwrap();
        assert_eq!(out, b"-1.500");
        for (seconds, nanos, text) in [
            (-2, 500_000_000, "-1.500000000"),
            (-1, 0, "-1"),
            (9_999_999_999, 1, "9999999999.000000001"),
            (-1, 1_500_000_000, "0.500000000"),
        ] {
            let mut out = Vec::new();
            write_instant(seconds, nanos, &mut out).unwrap();
            assert_eq!(out, text.as_bytes());
        }
    }
}