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

//! `Tuple(T1, T2, ...)` and named `Tuple(a T1, b T2)` columns.
//!
//! In the Native format a tuple column is the columns of its elements, one
//! after another, each with all the rows; the state prefixes of the elements
//! come first, in the same order (`SerializationTuple`). The geo types are
//! tuples and arrays of them: `Point` is `Tuple(Float64, Float64)`.

use std::{marker::PhantomData, sync::Arc};

use chrono_tz::Tz;
use either::Either;

use crate::{
    binary::{Encoder, ReadEx},
    errors::Result,
    types::{
        column::{
            column_data::{make_mut, ArcColumnData, BoxColumnData},
            ArcColumnWrapper, Column, ColumnData, Simple,
        },
        SqlType, Value, ValueRef,
    },
};

/// The element types of a geo `Point`.
pub(crate) const POINT: &str = "Tuple(Float64, Float64)";

pub(crate) struct TupleColumnData {
    pub(crate) elements: Vec<ArcColumnData>,
    /// The element names of a named tuple, `None` for an unnamed one.
    pub(crate) names: Vec<Option<String>>,
}

impl TupleColumnData {
    pub(crate) fn load<R: ReadEx>(
        reader: &mut R,
        elements: Vec<(Option<&str>, &str)>,
        size: usize,
        tz: Tz,
    ) -> Result<Self> {
        let mut columns = Vec::with_capacity(elements.len());
        let mut names = Vec::with_capacity(elements.len());
        for (name, type_name) in elements {
            columns.push(<dyn ColumnData>::load_data::<ArcColumnWrapper, _>(
                reader, type_name, size, tz,
            )?);
            names.push(name.map(unescape_name));
        }
        Ok(TupleColumnData {
            elements: columns,
            names,
        })
    }
}

impl ColumnData for TupleColumnData {
    fn save_prefix(&self, encoder: &mut Encoder) {
        for element in &self.elements {
            element.save_prefix(encoder);
        }
    }

    fn sql_type(&self) -> SqlType {
        SqlType::Tuple(
            self.names
                .iter()
                .zip(&self.elements)
                .map(|(name, element)| (name.clone(), element.sql_type().into()))
                .collect(),
        )
    }

    fn save(&self, encoder: &mut Encoder, start: usize, end: usize) {
        for element in &self.elements {
            element.save(encoder, start, end);
        }
    }

    fn len(&self) -> usize {
        self.elements[0].len()
    }

    fn push(&mut self, value: Value) {
        let Value::Tuple(values) = value else {
            panic!("value should be a tuple ({value:?})");
        };
        assert_eq!(
            values.len(),
            self.elements.len(),
            "a tuple of {} elements pushed into {}",
            values.len(),
            self.sql_type()
        );
        for (element, value) in self.elements.iter_mut().zip(values.iter()) {
            make_mut(element).push(value.clone());
        }
    }

    fn at(&self, index: usize) -> ValueRef<'_> {
        let values = self
            .elements
            .iter()
            .map(|element| element.at(index))
            .collect();
        ValueRef::Tuple(Arc::new(values))
    }

    fn clone_instance(&self) -> BoxColumnData {
        Box::new(Self {
            elements: self.elements.clone(),
            names: self.names.clone(),
        })
    }

    fn get_timezone(&self) -> Option<Tz> {
        self.elements
            .iter()
            .find_map(|element| element.get_timezone())
    }

    fn tuple_elements(&self) -> Option<&[ArcColumnData]> {
        Some(&self.elements)
    }

    /// A cast inside `Array` or `Map`: each element is cast as a column, so an
    /// unnamed tuple becomes a named one.
    fn cast_to(&self, _this: &ArcColumnData, target: &SqlType) -> Option<ArcColumnData> {
        let SqlType::Tuple(targets) = target else {
            return None;
        };
        if targets.len() != self.elements.len() {
            return None;
        }
        let elements = self
            .elements
            .iter()
            .zip(targets)
            .map(|(element, (_, target))| {
                // The same casts as for a column, so nesting a tuple in an array
                // or a map changes nothing about what it can be cast to.
                let column: Column<Simple> = Column {
                    name: String::new(),
                    data: element.clone(),
                    _marker: PhantomData,
                };
                column
                    .cast_to((*target).clone())
                    .ok()
                    .map(|column| column.data)
            })
            .collect::<Option<Vec<_>>>()?;
        Some(Arc::new(TupleColumnData {
            elements,
            names: targets.iter().map(|(name, _)| name.clone()).collect(),
        }))
    }
}

/// The elements of a `Tuple(...)` type name, with their names in a named
/// tuple, or `None` when it is not a tuple of at least one element.
pub(crate) fn parse_tuple_type(source: &str) -> Option<Vec<(Option<&str>, &str)>> {
    let body = source.strip_prefix("Tuple(")?.strip_suffix(')')?;
    let elements = split_top_level(body)?;
    elements.into_iter().map(parse_element).collect()
}

/// Splits at the commas outside parentheses and quotes, as in
/// `UInt8, Enum8('a,b' = 1), Map(String, UInt8)`.
pub(crate) fn split_top_level(body: &str) -> Option<Vec<&str>> {
    let mut parts = Vec::new();
    let mut depth = 0_usize;
    let mut quote: Option<char> = None;
    let mut escaped = false;
    let mut start = 0;
    for (pos, c) in body.char_indices() {
        if let Some(open) = quote {
            if escaped {
                escaped = false;
            } else if c == '\\' {
                escaped = true;
            } else if c == open {
                quote = None;
            }
            continue;
        }
        match c {
            '\'' | '`' => quote = Some(c),
            '(' => depth += 1,
            ')' => depth = depth.checked_sub(1)?,
            ',' if depth == 0 => {
                parts.push(body[start..pos].trim());
                start = pos + 1;
            }
            _ => {}
        }
    }
    if quote.is_some() || depth != 0 {
        return None;
    }
    parts.push(body[start..].trim());
    if parts.iter().any(|part| part.is_empty()) {
        return None;
    }
    Some(parts)
}

/// `a UInt8`, `` `a b` UInt8 `` or `UInt8`. An unnamed element type has no
/// space before its first parenthesis, a named one has its name there.
pub(crate) fn parse_element(element: &str) -> Option<(Option<&str>, &str)> {
    if let Some(rest) = element.strip_prefix('`') {
        let mut escaped = false;
        let end = rest.char_indices().find_map(|(pos, c)| {
            if escaped {
                escaped = false;
            } else if c == '\\' {
                escaped = true;
            } else if c == '`' {
                return Some(pos);
            }
            None
        })?;
        let type_name = rest[end + 1..].trim();
        return (!type_name.is_empty()).then_some((Some(&rest[..end]), type_name));
    }
    let head = element.split('(').next().unwrap_or(element);
    match head.find(' ') {
        Some(space) => {
            let type_name = element[space + 1..].trim();
            (!type_name.is_empty()).then_some((Some(&element[..space]), type_name))
        }
        None => Some((None, element)),
    }
}

/// The name of a tuple element as ClickHouse writes it in a type: plain, or
/// backquoted with the escapes of `writeBackQuotedString`.
pub(crate) fn element_name(name: &str) -> String {
    let plain = name
        .chars()
        .next()
        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
    if plain {
        return name.to_owned();
    }
    let mut quoted = String::with_capacity(name.len() + 2);
    quoted.push('`');
    for c in name.chars() {
        match c {
            '`' => quoted.push_str("\\`"),
            '\\' => quoted.push_str("\\\\"),
            '\n' => quoted.push_str("\\n"),
            '\t' => quoted.push_str("\\t"),
            '\r' => quoted.push_str("\\r"),
            '\0' => quoted.push_str("\\0"),
            '\x08' => quoted.push_str("\\b"),
            '\x0c' => quoted.push_str("\\f"),
            c if c.is_ascii_control() => quoted.push_str(&format!("\\x{:02X}", c as u8)),
            c => quoted.push(c),
        }
    }
    quoted.push('`');
    quoted
}

/// A backquoted element name without its escapes, the inverse of
/// [`element_name`]: `a\`b` is a`b.
pub(crate) fn unescape_name(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    let mut chars = name.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match chars.next() {
            Some('n') => out.push('\n'),
            Some('t') => out.push('\t'),
            Some('r') => out.push('\r'),
            Some('0') => out.push('\0'),
            Some('b') => out.push('\x08'),
            Some('f') => out.push('\x0c'),
            Some('x') => {
                let hex: String = chars.by_ref().take(2).collect();
                match u8::from_str_radix(&hex, 16) {
                    Ok(byte) => out.push(char::from(byte)),
                    Err(_) => {
                        out.push('x');
                        out.push_str(&hex);
                    }
                }
            }
            Some(other) => out.push(other),
            None => out.push('\\'),
        }
    }
    out
}

/// Whether the tuples in a `value` pushed into a column of `sql_type` have
/// that type's number of elements (and at least one), also inside
/// `Nullable`, `Array`, `Map` and `SimpleAggregateFunction`.
pub(crate) fn tuple_shape_fits(sql_type: &SqlType, value: &Value) -> bool {
    match (sql_type, value) {
        (SqlType::Tuple(types), Value::Tuple(values)) => {
            !types.is_empty()
                && types.len() == values.len()
                && types
                    .iter()
                    .zip(values.iter())
                    .all(|((_, element), value)| tuple_shape_fits(element, value))
        }
        (SqlType::Tuple(_), _) => false,
        (SqlType::Nullable(_), Value::Nullable(Either::Left(_))) => true,
        (SqlType::Nullable(inner), Value::Nullable(Either::Right(value))) => {
            tuple_shape_fits(inner, value)
        }
        (SqlType::Nullable(inner), value) => tuple_shape_fits(inner, value),
        (SqlType::Array(inner), Value::Array(_, values)) => {
            values.iter().all(|value| tuple_shape_fits(inner, value))
        }
        (SqlType::Map(keys, values), Value::Map(_, _, entries)) => entries
            .iter()
            .all(|(key, value)| tuple_shape_fits(keys, key) && tuple_shape_fits(values, value)),
        (SqlType::SimpleAggregateFunction(_, inner), value) => tuple_shape_fits(inner, value),
        _ => true,
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_parse_tuple_type() {
        assert_eq!(
            parse_tuple_type("Tuple(UInt8, String)"),
            Some(vec![(None, "UInt8"), (None, "String")])
        );
        assert_eq!(
            parse_tuple_type("Tuple(a UInt8, b Nullable(String))"),
            Some(vec![(Some("a"), "UInt8"), (Some("b"), "Nullable(String)")])
        );
        assert_eq!(
            parse_tuple_type("Tuple(`a b` Decimal(9, 2), Map(String, Tuple(UInt8, UInt8)))"),
            Some(vec![
                (Some("a b"), "Decimal(9, 2)"),
                (None, "Map(String, Tuple(UInt8, UInt8))")
            ])
        );
        assert_eq!(
            parse_tuple_type("Tuple(Enum8('a,b)' = 1, 'c' = 2), DateTime64(3, 'UTC'))"),
            Some(vec![
                (None, "Enum8('a,b)' = 1, 'c' = 2)"),
                (None, "DateTime64(3, 'UTC')")
            ])
        );
        assert_eq!(parse_tuple_type("Tuple()"), None);
        assert_eq!(parse_tuple_type("Tuple(UInt8,)"), None);
        assert_eq!(parse_tuple_type("Tuple(UInt8"), None);
        assert_eq!(parse_tuple_type("Tuple(Enum8('a)"), None);
        assert_eq!(parse_tuple_type("Array(UInt8)"), None);
    }

    #[test]
    fn test_element_name() {
        assert_eq!(element_name("a_1"), "a_1");
        assert_eq!(element_name("a b"), "`a b`");
        assert_eq!(element_name("1a"), "`1a`");
        assert_eq!(element_name("a`b"), "`a\\`b`");
        // A name read from a type and written back is unchanged.
        for name in ["a`b", "a\\b", "a\nb", "tab\there", "\x01", "plain"] {
            let written = format!("Tuple({} UInt8)", element_name(name));
            let elements = parse_tuple_type(&written).unwrap();
            assert_eq!(unescape_name(elements[0].0.unwrap()), name, "{written}");
        }
    }
}