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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
use std::{cmp, default::Default, fmt, io::Read, marker::PhantomData};

use chrono_tz::Tz;

use crate::{
    binary::{protocol, Encoder, ReadEx},
    errors::{Error, FromSqlError, Result},
    types::{
        column::{self, ArcColumnWrapper, Column, ColumnFrom},
        ColumnType, Complex, FromSql, Simple,
    },
};

pub use self::{
    block_info::BlockInfo,
    builder::{RCons, RNil, RowBuilder},
    compression::Compression,
    row::{Row, Rows},
};
pub(crate) use self::{
    chunk_iterator::ChunkIterator, compression::DEFAULT_ZSTD_LEVEL, row::BlockRef,
};

mod block_info;
mod builder;
mod chunk_iterator;
pub(crate) mod compressed;
mod compression;
pub(crate) mod pending;
mod row;

pub(crate) const INSERT_BLOCK_SIZE: usize = 1_048_576;

const DEFAULT_CAPACITY: usize = 100;

pub trait ColumnIdx {
    fn get_index<K: ColumnType>(&self, columns: &[Column<K>]) -> Result<usize>;
}

/// Represents Clickhouse Block
#[derive(Default)]
pub struct Block<K: ColumnType = Simple> {
    info: BlockInfo,
    columns: Vec<Column<K>>,
    capacity: usize,
}

impl<L: ColumnType, R: ColumnType> PartialEq<Block<R>> for Block<L> {
    fn eq(&self, other: &Block<R>) -> bool {
        if self.columns.len() != other.columns.len() {
            return false;
        }

        for i in 0..self.columns.len() {
            if self.columns[i] != other.columns[i] {
                return false;
            }
        }

        true
    }
}

impl<K: ColumnType> Clone for Block<K> {
    fn clone(&self) -> Self {
        Self {
            info: self.info,
            columns: self.columns.iter().map(|c| (*c).clone()).collect(),
            capacity: self.capacity,
        }
    }
}

impl<K: ColumnType> AsRef<Block<K>> for Block<K> {
    fn as_ref(&self) -> &Self {
        self
    }
}

impl ColumnIdx for usize {
    #[inline(always)]
    fn get_index<K: ColumnType>(&self, _: &[Column<K>]) -> Result<usize> {
        Ok(*self)
    }
}

impl ColumnIdx for &str {
    fn get_index<K: ColumnType>(&self, columns: &[Column<K>]) -> Result<usize> {
        match columns
            .iter()
            .enumerate()
            .find(|(_, column)| column.name() == *self)
        {
            None => Err(Error::FromSql(FromSqlError::OutOfRange)),
            Some((index, _)) => Ok(index),
        }
    }
}

impl ColumnIdx for String {
    fn get_index<K: ColumnType>(&self, columns: &[Column<K>]) -> Result<usize> {
        self.as_str().get_index(columns)
    }
}

impl Block {
    /// Constructs a new, empty `Block`.
    pub fn new() -> Self {
        Self::with_capacity(DEFAULT_CAPACITY)
    }

    /// Constructs a new, empty `Block` with the specified capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            info: Default::default(),
            columns: vec![],
            capacity,
        }
    }

    /// Reads a block in the Native format of protocol `revision`.
    pub(crate) fn load<R>(reader: &mut R, tz: Tz, compress: bool, revision: u64) -> Result<Self>
    where
        R: Read + ReadEx,
    {
        if compress {
            let mut cr = compressed::make(reader);
            Self::raw_load(&mut cr, tz, revision)
        } else {
            Self::raw_load(reader, tz, revision)
        }
    }

    fn raw_load<R>(reader: &mut R, tz: Tz, revision: u64) -> Result<Block<Simple>>
    where
        R: ReadEx,
    {
        let mut block = Block::new();
        block.info = BlockInfo::read(reader)?;

        let num_columns = reader.read_uvarint()?;
        let num_rows = reader.read_uvarint()?;

        for _ in 0..num_columns {
            let column = Column::read(reader, num_rows as usize, tz, revision)?;
            block.append_column(column);
        }

        Ok(block)
    }
}

impl<K: ColumnType> Block<K> {
    /// Return the number of rows in the current block.
    pub fn row_count(&self) -> usize {
        match self.columns.first() {
            None => 0,
            Some(column) => column.len(),
        }
    }

    /// Return the number of columns in the current block.
    pub fn column_count(&self) -> usize {
        self.columns.len()
    }

    /// This method returns a slice of columns.
    #[inline(always)]
    pub fn columns(&self) -> &[Column<K>] {
        &self.columns
    }

    fn append_column(&mut self, column: Column<K>) {
        let column_len = column.len();

        if !self.columns.is_empty() && self.row_count() != column_len {
            panic!("all columns in block must have same size.")
        }

        self.columns.push(column);
    }

    /// Get the value of a particular cell of the block.
    pub fn get<'a, T, I>(&'a self, row: usize, col: I) -> Result<T>
    where
        T: FromSql<'a>,
        I: ColumnIdx + Copy,
    {
        let column_index = col.get_index(self.columns())?;
        T::from_sql(self.columns[column_index].at(row))
    }

    /// Add new column into this block
    pub fn add_column<S>(self, name: &str, values: S) -> Self
    where
        S: ColumnFrom,
    {
        self.column(name, values)
    }

    /// Add new column into this block
    pub fn column<S>(mut self, name: &str, values: S) -> Self
    where
        S: ColumnFrom,
    {
        let data = S::column_from::<ArcColumnWrapper>(values);
        let column = column::new_column(name, data);

        self.append_column(column);
        self
    }

    /// Returns true if the block contains no elements.
    pub fn is_empty(&self) -> bool {
        self.columns.is_empty()
    }

    /// This method returns a iterator of rows.
    pub fn rows(&self) -> Rows<'_, K> {
        Rows {
            row: 0,
            block_ref: BlockRef::Borrowed(self),
            kind: PhantomData,
        }
    }

    /// This method is a convenient way to pass row into a block.
    pub fn push<B: RowBuilder>(&mut self, row: B) -> Result<()> {
        row.apply(self)
    }

    /// This method finds a column by identifier.
    pub fn get_column<I>(&self, col: I) -> Result<&Column<K>>
    where
        I: ColumnIdx + Copy,
    {
        let column_index = col.get_index(self.columns())?;
        let column = &self.columns[column_index];
        Ok(column)
    }
}

impl Block<Simple> {
    pub(crate) fn concat(blocks: &[Self]) -> Block<Complex> {
        let first = blocks.first().expect("blocks should not be empty.");

        for block in blocks {
            assert_eq!(
                first.column_count(),
                block.column_count(),
                "all columns should have the same size."
            );
        }

        let num_columns = first.column_count();
        let mut columns = Vec::with_capacity(num_columns);
        for i in 0_usize..num_columns {
            let chunks = blocks.iter().map(|block| &block.columns[i]);
            columns.push(Column::concat(chunks));
        }

        Block {
            info: first.info,
            columns,
            capacity: blocks.iter().map(|b| b.capacity).sum(),
        }
    }
}

impl<K: ColumnType> Block<K> {
    pub(crate) fn cast_to(&self, header: &Block<K>) -> Result<Self> {
        let info = self.info;
        let mut columns = self.columns.clone();
        columns.reverse();

        if header.column_count() != columns.len() {
            return Err(Error::FromSql(FromSqlError::OutOfRange));
        }

        let mut new_columns = Vec::with_capacity(columns.len());
        for column in header.columns() {
            let dst_type = column.sql_type();
            let old_column = columns.pop().unwrap();
            let new_column = old_column.cast_to(dst_type)?;
            new_columns.push(new_column);
        }

        Ok(Block {
            info,
            columns: new_columns,
            capacity: self.capacity,
        })
    }

    /// Writes the block in the Native format of this client's revision.
    #[cfg(test)]
    pub(crate) fn write(&self, encoder: &mut Encoder, compression: Compression) -> Result<()> {
        let revision = crate::client_info::CLICK_HOUSE_REVISION;
        self.write_with(
            encoder,
            compression,
            compression::DEFAULT_ZSTD_LEVEL,
            revision,
        )
    }

    /// Writes the block in the Native format of `revision`.
    #[cfg(test)]
    pub(crate) fn write_at(
        &self,
        encoder: &mut Encoder,
        compression: Compression,
        revision: u64,
    ) -> Result<()> {
        self.write_with(
            encoder,
            compression,
            compression::DEFAULT_ZSTD_LEVEL,
            revision,
        )
    }

    fn write_with(
        &self,
        encoder: &mut Encoder,
        compression: Compression,
        zstd_level: i32,
        revision: u64,
    ) -> Result<()> {
        if !compression.is_enabled() {
            self.write_raw(encoder, revision);
            return Ok(());
        }

        let mut raw = Encoder::new();
        self.write_raw(&mut raw, revision);
        compression::compress(
            compression,
            zstd_level,
            raw.get_buffer_ref(),
            encoder.buffer_mut(),
        )
    }

    fn write_raw(&self, encoder: &mut Encoder, revision: u64) {
        self.info.write(encoder);
        encoder.uvarint(self.column_count() as u64);
        encoder.uvarint(self.row_count() as u64);

        for column in &self.columns {
            column.write(encoder, revision);
        }
    }

    /// Sends the block in the Native format of protocol `revision`.
    pub(crate) fn send_data(
        &self,
        encoder: &mut Encoder,
        compression: Compression,
        zstd_level: i32,
        revision: u64,
    ) -> Result<()> {
        encoder.uvarint(protocol::CLIENT_DATA);
        encoder.string(""); // temporary table
        self.write_with(encoder, compression, zstd_level, revision)
    }

    pub(crate) fn chunks(self, n: usize) -> ChunkIterator<K> {
        ChunkIterator::new(n, self)
    }
}

impl<K: ColumnType> fmt::Debug for Block<K> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let titles: Vec<&str> = self.columns.iter().map(|column| column.name()).collect();

        let cells: Vec<_> = self.columns.iter().map(|col| text_cells(col)).collect();

        let titles_len: Vec<_> = titles
            .iter()
            .map(|t| t.chars().count())
            .zip(cells.iter().map(|w| column_width(w)))
            .map(|(a, b)| cmp::max(a, b))
            .collect();

        print_line(f, &titles_len, "\n\u{250c}", '┬', "\u{2510}\n")?;

        for (i, title) in titles.iter().enumerate() {
            write!(f, "\u{2502}{:>width$} ", title, width = titles_len[i] + 1)?;
        }
        write!(f, "\u{2502}")?;

        if self.row_count() > 0 {
            print_line(f, &titles_len, "\n\u{251c}", '┼', "\u{2524}\n")?;
        }

        for j in 0..self.row_count() {
            for (i, col) in cells.iter().enumerate() {
                write!(f, "\u{2502}{:>width$} ", col[j], width = titles_len[i] + 1)?;
            }

            let new_line = (j + 1) != self.row_count();
            write!(f, "\u{2502}{}", if new_line { "\n" } else { "" })?;
        }

        print_line(f, &titles_len, "\n\u{2514}", 'â”´', "\u{2518}")
    }
}

fn column_width(column: &[String]) -> usize {
    column.iter().map(|cell| cell.len()).max().unwrap_or(0)
}

fn print_line(
    f: &mut fmt::Formatter,
    lens: &[usize],
    left: &str,
    center: char,
    right: &str,
) -> fmt::Result {
    write!(f, "{left}")?;
    for (i, len) in lens.iter().enumerate() {
        if i != 0 {
            write!(f, "{center}")?;
        }

        write!(f, "{:\u{2500}>width$}", "", width = len + 2)?;
    }
    write!(f, "{right}")
}

fn text_cells<K: ColumnType>(data: &Column<K>) -> Vec<String> {
    (0..data.len()).map(|i| format!("{}", data.at(i))).collect()
}

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

    use super::*;
    use crate::{row, types::column::datetime64::DEFAULT_TZ};

    #[test]
    fn test_write_default() {
        let expected = [1_u8, 0, 2, 255, 255, 255, 255, 0, 0, 0];
        let mut encoder = Encoder::new();
        Block::<Simple>::default()
            .write(&mut encoder, Compression::None)
            .unwrap();
        assert_eq!(encoder.get_buffer_ref(), &expected)
    }

    #[test]
    fn test_compress_block() {
        let expected = vec![
            245_u8, 5, 222, 235, 225, 158, 59, 108, 225, 31, 65, 215, 66, 66, 36, 92, 130, 34, 0,
            0, 0, 23, 0, 0, 0, 240, 8, 1, 0, 2, 255, 255, 255, 255, 0, 1, 1, 1, 115, 6, 83, 116,
            114, 105, 110, 103, 3, 97, 98, 99,
        ];

        let block = Block::<Simple>::new().column("s", vec!["abc"]);

        // The bytes of revision 54429, before the custom serialization flag.
        let mut encoder = Encoder::new();
        block
            .write_with(
                &mut encoder,
                Compression::Lz4,
                compression::DEFAULT_ZSTD_LEVEL,
                54429,
            )
            .unwrap();

        let actual = encoder.get_buffer();
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_decompress_block() {
        let expected = Block::<Simple>::new().column("s", vec!["abc"]);

        let source = [
            245_u8, 5, 222, 235, 225, 158, 59, 108, 225, 31, 65, 215, 66, 66, 36, 92, 130, 34, 0,
            0, 0, 23, 0, 0, 0, 240, 8, 1, 0, 2, 255, 255, 255, 255, 0, 1, 1, 1, 115, 6, 83, 116,
            114, 105, 110, 103, 3, 97, 98, 99,
        ];

        let mut cursor = Cursor::new(&source[..]);
        let actual = Block::load(
            &mut cursor,
            Tz::UTC,
            true,
            54429, // the revision of these bytes
        )
        .unwrap();

        assert_eq!(actual, expected);
    }

    #[test]
    fn test_compressed_round_trip() {
        let strings: Vec<String> = (0..300_000).map(|i| format!("value {i}")).collect();
        let numbers: Vec<u64> = (0..300_000).collect();
        let expected = Block::<Simple>::new()
            .column("s", strings)
            .column("n", numbers);

        for compression in [Compression::Lz4, Compression::Zstd] {
            let mut encoder = Encoder::new();
            expected.write(&mut encoder, compression).unwrap();

            let mut cursor = Cursor::new(encoder.get_buffer_ref());
            let actual = Block::load(
                &mut cursor,
                Tz::UTC,
                true,
                crate::client_info::CLICK_HOUSE_REVISION,
            )
            .unwrap();
            assert_eq!(actual, expected, "{compression}");
        }
    }

    #[test]
    fn test_strings_at_both_layouts() {
        // Strings alone and inside Nullable, Array, Map and Tuple, before and
        // from 54492, where they come as their sizes, then their bytes.
        let maps: Vec<HashMap<String, u8>> = (0..3_u8)
            .map(|i| (0..i).map(|k| ("k".repeat(usize::from(k)), k)).collect())
            .collect();
        let expected = Block::<Simple>::new()
            .column("s", vec!["", "a", "bcd"])
            .column("n", vec![None, Some("x"), Some("")])
            .column("a", vec![vec!["p", "q"], vec![], vec!["", "r"]])
            .column("m", maps)
            .column("t", vec![("u", 1_u8), ("", 2), ("w", 3)]);
        let mut layouts = Vec::new();
        for revision in [54491, 54492] {
            let mut encoder = Encoder::new();
            expected
                .write_with(&mut encoder, Compression::None, 0, revision)
                .unwrap();
            let bytes = encoder.get_buffer();
            let mut cursor = Cursor::new(&bytes[..]);
            let actual = Block::load(&mut cursor, Tz::UTC, false, revision).unwrap();
            assert_eq!(actual, expected, "{revision}");
            assert_eq!(cursor.position() as usize, bytes.len(), "{revision}");
            layouts.push(bytes);
        }
        assert_ne!(layouts[0], layouts[1]);

        // At 54492 nested strings are where each one ends, then their bytes,
        // after the offsets of an array, the null map or the other elements
        // of a tuple (`propagate_types_serialization_versions_to_nested_types`).
        let mut array = Encoder::new();
        for offset in [2_u64, 2, 4] {
            array.write(offset);
        }
        for end in [1_u64, 2, 2, 3] {
            array.write(end);
        }
        array.write_bytes(b"pqr");
        let mut nullable = Encoder::new();
        nullable.write_bytes(&[1, 0, 0]);
        for end in [0_u64, 1, 1] {
            nullable.write(end);
        }
        nullable.write_bytes(b"x");
        let mut tuple = Encoder::new();
        for end in [1_u64, 1, 2] {
            tuple.write(end);
        }
        tuple.write_bytes(b"uw");
        tuple.write_bytes(&[1, 2, 3]);
        let fixtures = [
            (expected.get_column("a").unwrap(), array.get_buffer()),
            (expected.get_column("n").unwrap(), nullable.get_buffer()),
            (expected.get_column("t").unwrap(), tuple.get_buffer()),
        ];
        for (column, data) in fixtures {
            let mut encoder = Encoder::new();
            column.write(&mut encoder, 54492);
            let bytes = encoder.get_buffer();
            assert!(bytes.ends_with(&data), "{}: {bytes:?}", column.name());
        }
    }

    #[test]
    fn test_read_empty_block() {
        let source = [1, 0, 2, 255, 255, 255, 255, 0, 0, 0];
        let mut cursor = Cursor::new(&source[..]);
        match Block::<Simple>::load(&mut cursor, *DEFAULT_TZ, false, 54429) {
            Ok(block) => assert!(block.is_empty()),
            Err(_) => unreachable!(),
        }
    }

    #[test]
    fn test_custom_serialization_is_an_error() {
        // Block info, one column of one row, a UInt8 flagged as custom.
        let mut source = vec![1, 0, 2, 255, 255, 255, 255, 0, 1, 1];
        source.extend([1, b's', 5, b'U', b'I', b'n', b't', b'8', 1, 42]);
        // Before sparse columns (54465), a set flag is an error.
        let err = Block::<Simple>::load(&mut Cursor::new(&source[..]), Tz::UTC, false, 54459)
            .unwrap_err();
        assert!(err.to_string().contains("custom serialization"), "{err}");
        // From then on the kind follows: 42 is none of them.
        let revision = crate::client_info::CLICK_HOUSE_REVISION;
        let err = Block::<Simple>::load(&mut Cursor::new(&source[..]), Tz::UTC, false, revision)
            .unwrap_err();
        assert!(err.to_string().contains("serialization kind 42"), "{err}");

        // Without the flag, the same column reads.
        source[18] = 0;
        let block =
            Block::<Simple>::load(&mut Cursor::new(&source[..]), Tz::UTC, false, revision).unwrap();
        let value: u8 = block.get(0, "s").unwrap();
        assert_eq!(value, 42);
    }

    #[test]
    fn test_empty() {
        assert!(Block::<Simple>::default().is_empty())
    }

    #[test]
    fn test_column_and_rows() {
        let block = Block::<Simple>::new()
            .column("hello_id", vec![5_u32, 6_u32])
            .column("value", vec!["lol", "zuz"]);

        assert_eq!(block.column_count(), 2);
        assert_eq!(block.row_count(), 2);
    }

    #[test]
    fn test_concat() {
        let block_a = make_block();
        let block_b = make_block();

        let actual = Block::concat(&[block_a, block_b]);
        assert_eq!(actual.row_count(), 4);
        assert_eq!(actual.column_count(), 1);

        assert_eq!(
            "5446d186-4e90-4dd8-8ec1-f9a436834613".to_string(),
            actual.get::<String, _>(0, 0).unwrap()
        );
        assert_eq!(
            "f7cf31f4-7f37-4e27-91c0-5ac0ad0b145b".to_string(),
            actual.get::<String, _>(1, 0).unwrap()
        );
        assert_eq!(
            "5446d186-4e90-4dd8-8ec1-f9a436834613".to_string(),
            actual.get::<String, _>(2, 0).unwrap()
        );
        assert_eq!(
            "f7cf31f4-7f37-4e27-91c0-5ac0ad0b145b".to_string(),
            actual.get::<String, _>(3, 0).unwrap()
        );
    }

    fn make_block() -> Block {
        Block::new().column(
            "9b96ad8b-488a-4fef-8087-8a9ae4800f00",
            vec![
                "5446d186-4e90-4dd8-8ec1-f9a436834613".to_string(),
                "f7cf31f4-7f37-4e27-91c0-5ac0ad0b145b".to_string(),
            ],
        )
    }

    #[test]
    fn test_chunks_of_arrays_and_maps_are_written_as_their_rows() {
        // An insert writes a large block chunk by chunk; each chunk is a
        // block of its rows, arrays and maps too, at both string layouts.
        let rows = 7_u8;
        let arrays: Vec<Vec<u8>> = (0..rows).map(|i| (0..i % 3).collect()).collect();
        let strings: Vec<Vec<String>> = (0..rows)
            .map(|i| (0..i % 4).map(|j| format!("{i}.{j}")).collect())
            .collect();
        let maps: Vec<HashMap<String, u8>> = (0..rows)
            .map(|i| (0..i % 2 + 1).map(|k| (format!("k{k}"), i)).collect())
            .collect();
        let block = Block::<Simple>::new()
            .column("a", arrays.clone())
            .column("s", strings.clone())
            .column("m", maps.clone());
        for revision in [54491, 54492] {
            let mut start = 0_usize;
            for chunk in block.clone().chunks(3) {
                let end = start + chunk.row_count();
                let mut encoder = Encoder::new();
                chunk
                    .write_with(&mut encoder, Compression::None, 0, revision)
                    .unwrap();
                let bytes = encoder.get_buffer();
                let read =
                    Block::load(&mut Cursor::new(&bytes[..]), Tz::UTC, false, revision).unwrap();
                let expected = Block::<Simple>::new()
                    .column("a", arrays[start..end].to_vec())
                    .column("s", strings[start..end].to_vec())
                    .column("m", maps[start..end].to_vec());
                assert_eq!(read, expected, "{revision}: rows {start}..{end}");
                start = end;
            }
            assert_eq!(start, usize::from(rows));
        }
    }

    #[test]
    fn test_chunks() {
        let first = Block::new().column("A", vec![1, 2]);
        let second = Block::new().column("A", vec![3, 4]);
        let third = Block::new().column("A", vec![5]);

        let block = Block::<Simple>::new().column("A", vec![1, 2, 3, 4, 5]);
        let mut iter = block.chunks(2);

        assert_eq!(Some(first), iter.next());
        assert_eq!(Some(second), iter.next());
        assert_eq!(Some(third), iter.next());
        assert_eq!(None, iter.next());
    }

    #[test]
    fn test_chunks_of_empty_block() {
        let block = Block::default();
        assert_eq!(1, block.clone().chunks(100_500).count());
        assert_eq!(Some(block.clone()), block.chunks(100_500).next());
    }

    #[test]
    fn test_rows() {
        let expected = vec![1_u8, 2, 3];
        let block = Block::<Simple>::new().column("A", vec![1_u8, 2, 3]);
        let actual: Vec<u8> = block.rows().map(|row| row.get("A").unwrap()).collect();
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_write_and_read() {
        let block = Block::<Simple>::new().column("y", vec![Some(1_u8), None]);

        let mut encoder = Encoder::new();
        block.write(&mut encoder, Compression::None).unwrap();

        let mut reader = Cursor::new(encoder.get_buffer_ref());
        let rblock = Block::load(
            &mut reader,
            *DEFAULT_TZ,
            false,
            crate::client_info::CLICK_HOUSE_REVISION,
        )
        .unwrap();

        assert_eq!(block, rblock);
    }

    #[test]
    fn test_insert_str_array() {
        let expected: Vec<String> = vec!["A".into(), "B".into()];
        let mut block = Block::new();
        block
            .push(row! {
                  tags: expected.clone(),
            })
            .unwrap();

        let actual: Vec<String> = block.get(0, 0).unwrap();
        assert_eq!(actual, expected);
    }
}