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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/*
 * 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
 */

//! Columns of a special serialization kind (`SerializationInfo`), which the
//! server sends to clients that know them:
//!
//! - sparse (revision 54465; Nullable ones from 54483,
//!   `SerializationSparse`): a column of mostly defaults comes as the number
//!   of defaults before each other value, then those values alone;
//! - replicated (54482, `SerializationReplicated`): the results of a `JOIN`,
//!   `ARRAY JOIN` or a lambda's captures come as an index per row into a
//!   column of the distinct rows, which may be sparse itself.
//!
//! The reader turns both into ordinary columns. A tuple may have sparse
//! elements (`SerializationInfoTuple`).

use std::{borrow::Cow, sync::Arc};

use chrono_tz::Tz;

use crate::{
    binary::ReadEx,
    errors::{DriverError, Error, Result},
    types::column::{
        column_data::{ArcColumnData, ColumnData},
        gather::{gather, gather_into_nullable, nullable_inner},
        tuple::{parse_tuple_type, unescape_name, TupleColumnData, POINT},
        ArcColumnWrapper,
    },
};

/// Marks the last group of defaults (`END_OF_GRANULE_FLAG`).
pub(super) const END_OF_GRANULE: u64 = 1 << 62;

/// `SerializationKind`: the kinds in a stack of them.
const KIND_DEFAULT: u8 = 0;
const KIND_SPARSE: u8 = 1;
const KIND_REPLICATED: u8 = 3;

/// The serialization kinds of a column, as the server writes them after its
/// custom flag (`serialializeKindStackBinary`): the stack of the column and,
/// for a tuple, the kinds of each element after it.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Kinds {
    pub(super) sparse: bool,
    pub(super) replicated: bool,
    pub(super) elements: Vec<Kinds>,
}

impl Kinds {
    pub(crate) fn read<R: ReadEx>(reader: &mut R, type_name: &str) -> Result<Kinds> {
        // The stacks of their own, or 5 and the kinds of the stack.
        let stack = match reader.read_scalar::<u8>()? {
            0 => vec![KIND_DEFAULT],
            1 => vec![KIND_DEFAULT, KIND_SPARSE],
            4 => vec![KIND_DEFAULT, KIND_REPLICATED],
            5 => {
                let count = reader.read_uvarint()?;
                if count > 4 {
                    return Err(unsupported(type_name, &format!("a stack of {count} kinds")));
                }
                (0..count)
                    .map(|_| reader.read_scalar::<u8>())
                    .collect::<Result<_>>()?
            }
            kind => return Err(unsupported(type_name, &format!("kind {kind}"))),
        };
        // Sparse inside replicated, as `canonical_kind_order` has them.
        let (sparse, replicated) = match stack[..] {
            [KIND_DEFAULT] => (false, false),
            [KIND_DEFAULT, KIND_SPARSE] => (true, false),
            [KIND_DEFAULT, KIND_REPLICATED] => (false, true),
            [KIND_DEFAULT, KIND_SPARSE, KIND_REPLICATED] => (true, true),
            _ => return Err(unsupported(type_name, &format!("kinds {stack:?}"))),
        };
        let elements = match tuple_elements(type_name) {
            Some(elements) => elements
                .into_iter()
                .map(|(_, element)| Kinds::read(reader, element))
                .collect::<Result<_>>()?,
            None => Vec::new(),
        };
        Ok(Kinds {
            sparse,
            replicated,
            elements,
        })
    }
}

fn unsupported(type_name: &str, what: &str) -> Error {
    deserialize_error(format!(
        "serialization {what} of {type_name} is not supported"
    ))
}

/// The elements of a tuple type, a `Point` being `Tuple(Float64, Float64)`.
pub(super) fn tuple_elements(type_name: &str) -> Option<Vec<(Option<&str>, &str)>> {
    parse_tuple_type(if type_name == "Point" {
        POINT
    } else {
        type_name
    })
}

fn deserialize_error(message: String) -> Error {
    Error::Driver(DriverError::Deserialize(Cow::Owned(message)))
}

/// Loads `size` rows of a column of `type_name` serialized as `kinds` say.
pub(crate) fn load<R: ReadEx>(
    reader: &mut R,
    type_name: &str,
    size: usize,
    tz: Tz,
    kinds: &Kinds,
) -> Result<ArcColumnData> {
    if kinds.replicated {
        return load_replicated(reader, type_name, size, tz, kinds);
    }
    if kinds.sparse {
        let rows = read_offsets(reader, size)?;
        log::trace!(
            "[sparse] {type_name}: {} values among {size} rows",
            rows.len()
        );
        let mut picks = vec![None; size];
        for (index, row) in rows.iter().enumerate() {
            picks[*row] = Some(index);
        }
        // The values of a Nullable one are of its inner type: all of them are
        // there, and the defaults are NULL.
        if let Some(inner_type) = nullable_inner(type_name) {
            let values = <dyn ColumnData>::load_data::<ArcColumnWrapper, _>(
                reader,
                inner_type,
                rows.len(),
                tz,
            )?;
            return gather_into_nullable(&*values, &picks, type_name, inner_type, tz);
        }
        let values =
            <dyn ColumnData>::load_data::<ArcColumnWrapper, _>(reader, type_name, rows.len(), tz)?;
        return gather(&*values, &picks, type_name, tz);
    }
    match tuple_elements(type_name) {
        // Elements one after another, each as its kinds say.
        Some(elements) if elements.len() == kinds.elements.len() => {
            let mut columns = Vec::with_capacity(elements.len());
            let mut names = Vec::with_capacity(elements.len());
            for ((name, element), kinds) in elements.into_iter().zip(&kinds.elements) {
                columns.push(load(reader, element, size, tz, kinds)?);
                names.push(name.map(unescape_name));
            }
            Ok(Arc::new(TupleColumnData {
                elements: columns,
                names,
            }))
        }
        _ => <dyn ColumnData>::load_data::<ArcColumnWrapper, _>(reader, type_name, size, tz),
    }
}

/// The number of rows, the width of an index (1, 2, 4 or 8 bytes), an index
/// per row, the number of distinct rows, and those rows.
fn load_replicated<R: ReadEx>(
    reader: &mut R,
    type_name: &str,
    size: usize,
    tz: Tz,
    kinds: &Kinds,
) -> Result<ArcColumnData> {
    let rows = read_count(reader)?;
    if rows != size {
        return Err(deserialize_error(format!(
            "a replicated column of {size} rows has {rows} indexes"
        )));
    }
    let width: u8 = reader.read_scalar()?;
    let mut picks = Vec::with_capacity(size.min(1 << 20));
    for _ in 0..size {
        let index = match width {
            1 => u64::from(reader.read_scalar::<u8>()?),
            2 => u64::from(reader.read_scalar::<u16>()?),
            4 => u64::from(reader.read_scalar::<u32>()?),
            8 => reader.read_scalar::<u64>()?,
            _ => {
                return Err(deserialize_error(format!(
                    "a replicated column has indexes of {width} bytes"
                )))
            }
        };
        picks.push(Some(usize::try_from(index).unwrap_or(usize::MAX)));
    }
    let distinct = read_count(reader)?;
    if let Some(Some(index)) = picks.iter().find(|pick| pick.unwrap_or(0) >= distinct) {
        return Err(deserialize_error(format!(
            "a replicated column of {distinct} distinct rows points to row {index}"
        )));
    }
    log::trace!("[replicated] {type_name}: {distinct} distinct among {size} rows");
    let nested_kinds = Kinds {
        replicated: false,
        ..kinds.clone()
    };
    let nested = load(reader, type_name, distinct, tz, &nested_kinds)?;
    gather(&*nested, &picks, type_name, tz)
}

fn read_count<R: ReadEx>(reader: &mut R) -> Result<usize> {
    usize::try_from(reader.read_uvarint()?).map_err(|_| Error::Driver(DriverError::Overflow))
}

/// The rows of the values of a sparse column of `size` rows: before each
/// value the number of defaults, and last the defaults that end the column.
fn read_offsets<R: ReadEx>(reader: &mut R, size: usize) -> Result<Vec<usize>> {
    let mut rows = Vec::new();
    let mut row = 0_usize;
    loop {
        let group = reader.read_uvarint()?;
        let defaults = usize::try_from(group & !END_OF_GRANULE).unwrap_or(usize::MAX);
        row = row.saturating_add(defaults);
        if group & END_OF_GRANULE != 0 {
            break;
        }
        if row >= size {
            return Err(deserialize_error(format!(
                "a sparse column of {size} rows has a value at row {row}"
            )));
        }
        rows.push(row);
        row += 1;
    }
    if row != size {
        return Err(deserialize_error(format!(
            "a sparse column of {size} rows ends at row {row}"
        )));
    }
    Ok(rows)
}

#[cfg(test)]
mod test {
    use std::io::{self, Cursor};

    use super::*;
    use crate::binary::Encoder;
    use crate::types::Value;

    #[test]
    fn test_sparse_columns() {
        // Five rows: 0, 7, 0, 0, 9 of UInt32, and a tuple with a sparse second
        // element: (1, ''), (2, 'x'), (3, '').
        let mut encoder = Encoder::new();
        encoder.write(1_u8); // sparse
        encoder.uvarint(1); // one default, then a value
        encoder.uvarint(2); // two defaults, then a value
        encoder.uvarint(END_OF_GRANULE); // no defaults at the end
        encoder.write(7_u32);
        encoder.write(9_u32);
        encoder.write(0_u8); // the tuple is not sparse
        encoder.write(0_u8); // its first element is not
        encoder.write(1_u8); // its second element is
        for n in [1_u8, 2, 3] {
            encoder.write(n);
        }
        encoder.uvarint(1);
        encoder.uvarint(END_OF_GRANULE | 1);
        encoder.string("x");
        let bytes = encoder.get_buffer();
        let mut reader = Cursor::new(&bytes[..]);

        let kinds = Kinds::read(&mut reader, "UInt32").unwrap();
        let column = load(&mut reader, "UInt32", 5, Tz::UTC, &kinds).unwrap();
        let values: Vec<Value> = (0..5).map(|row| Value::from(column.at(row))).collect();
        let expected: Vec<Value> = [0_u32, 7, 0, 0, 9].into_iter().map(Value::from).collect();
        assert_eq!(values, expected);

        let tuple = "Tuple(UInt8, String)";
        let kinds = Kinds::read(&mut reader, tuple).unwrap();
        let column = load(&mut reader, tuple, 3, Tz::UTC, &kinds).unwrap();
        assert_eq!(column.sql_type().to_string(), tuple);
        let texts: Vec<String> = (0..3)
            .map(|row| Value::from(column.at(row)).to_string())
            .collect();
        assert_eq!(texts, ["(1, )", "(2, x)", "(3, )"]);
        assert_eq!(reader.position() as usize, bytes.len());

        // Offsets that do not cover the column are an error.
        let mut encoder = Encoder::new();
        encoder.uvarint(END_OF_GRANULE | 2);
        let bytes = encoder.get_buffer();
        assert!(read_offsets(&mut Cursor::new(&bytes[..]), 3).is_err());
        let mut encoder = Encoder::new();
        encoder.uvarint(5);
        let bytes = encoder.get_buffer();
        assert!(read_offsets(&mut Cursor::new(&bytes[..]), 3).is_err());
    }

    #[test]
    fn test_a_point_with_a_sparse_coordinate() {
        // Two Points, (0, 1.5) and (2.5, 3.5): x is sparse, y is not.
        let mut encoder = Encoder::new();
        encoder.write(0_u8); // the point
        encoder.write(1_u8); // x
        encoder.write(0_u8); // y
        encoder.uvarint(1);
        encoder.uvarint(END_OF_GRANULE);
        encoder.write(2.5_f64);
        encoder.write(1.5_f64);
        encoder.write(3.5_f64);
        let bytes = encoder.get_buffer();
        let mut reader = Cursor::new(&bytes[..]);
        let kinds = Kinds::read(&mut reader, "Point").unwrap();
        let column = load(&mut reader, "Point", 2, Tz::UTC, &kinds).unwrap();
        assert_eq!(reader.position() as usize, bytes.len());
        let texts: Vec<String> = (0..2)
            .map(|row| Value::from(column.at(row)).to_string())
            .collect();
        assert_eq!(texts, ["(0, 1.5)", "(2.5, 3.5)"]);
    }

    #[test]
    fn test_replicated_columns() {
        // Four UInt32 rows from two distinct ones: 20, 10, 20, 20.
        let mut encoder = Encoder::new();
        encoder.write(4_u8); // replicated
        encoder.uvarint(4);
        encoder.write(1_u8); // indexes of one byte
        for index in [1_u8, 0, 1, 1] {
            encoder.write(index);
        }
        encoder.uvarint(2);
        encoder.write(10_u32);
        encoder.write(20_u32);
        // Replicated over sparse: three rows from (0, 5): 0, 5, 0.
        for kind in [5_u8, 3, 0, 1, 3] {
            encoder.write(kind);
        }
        encoder.uvarint(3);
        encoder.write(1_u8);
        for index in [0_u8, 1, 0] {
            encoder.write(index);
        }
        encoder.uvarint(2);
        encoder.uvarint(1);
        encoder.uvarint(END_OF_GRANULE);
        encoder.write(5_u64);
        // Nullable strings from (NULL, 'x'): 'x', 'x', NULL.
        encoder.write(4_u8);
        encoder.uvarint(3);
        encoder.write(2_u8); // indexes of two bytes
        for index in [1_u16, 1, 0] {
            encoder.write(index);
        }
        encoder.uvarint(2);
        encoder.write(1_u8);
        encoder.write(0_u8);
        encoder.string("");
        encoder.string("x");
        let bytes = encoder.get_buffer();
        let mut reader = Cursor::new(&bytes[..]);

        for (type_name, rows, expected) in [
            ("UInt32", 4, vec!["20", "10", "20", "20"]),
            ("UInt64", 3, vec!["0", "5", "0"]),
            ("Nullable(String)", 3, vec!["x", "x", "NULL"]),
        ] {
            let kinds = Kinds::read(&mut reader, type_name).unwrap();
            let column = load(&mut reader, type_name, rows, Tz::UTC, &kinds).unwrap();
            assert_eq!(column.sql_type().to_string(), type_name);
            let texts: Vec<String> = (0..rows)
                .map(|row| Value::from(column.at(row)).to_string())
                .collect();
            assert_eq!(texts, expected, "{type_name}");
        }
        assert_eq!(reader.position() as usize, bytes.len());

        // An index past the distinct rows is an error.
        let mut encoder = Encoder::new();
        encoder.uvarint(1);
        encoder.write(1_u8);
        encoder.write(3_u8);
        encoder.uvarint(2);
        let bytes = encoder.get_buffer();
        let kinds = Kinds {
            sparse: false,
            replicated: true,
            elements: Vec::new(),
        };
        let result = load(&mut Cursor::new(&bytes[..]), "UInt8", 1, Tz::UTC, &kinds);
        let err = result.err().expect("an index past the distinct rows");
        assert!(err.to_string().contains("points to row 3"), "{err}");
    }

    #[test]
    fn test_sparse_times_keep_their_type() {
        // Three rows of DateTime64(3, 'Europe/Berlin'): default, -1 tick, default;
        // and of DateTime('Europe/Berlin'): 5 s, default, default.
        let mut encoder = Encoder::new();
        encoder.uvarint(1);
        encoder.uvarint(END_OF_GRANULE | 1);
        encoder.write(-1_i64);
        encoder.uvarint(0);
        encoder.uvarint(END_OF_GRANULE | 2);
        encoder.write(5_u32);
        let bytes = encoder.get_buffer();
        let mut reader = Cursor::new(&bytes[..]);
        let sparse = Kinds {
            sparse: true,
            replicated: false,
            elements: Vec::new(),
        };
        for (type_name, expected) in [
            ("DateTime64(3, 'Europe/Berlin')", [0_i64, -1, 0]),
            ("DateTime('Europe/Berlin')", [5, 0, 0]),
        ] {
            let column = load(&mut reader, type_name, 3, Tz::UTC, &sparse).unwrap();
            let dense = <dyn ColumnData>::load_data::<ArcColumnWrapper, _>(
                &mut io::repeat(0),
                type_name,
                1,
                Tz::UTC,
            )
            .unwrap();
            assert_eq!(column.sql_type(), dense.sql_type(), "{type_name}");
            assert_eq!(column.get_timezone(), dense.get_timezone(), "{type_name}");
            let mut saved = Encoder::new();
            column.save(&mut saved, 0, 3);
            let mut wanted = Encoder::new();
            for ticks in expected {
                match type_name.starts_with("DateTime64") {
                    true => wanted.write(ticks),
                    false => wanted.write(ticks as u32),
                }
            }
            assert_eq!(saved.get_buffer(), wanted.get_buffer(), "{type_name}");
        }
    }
}