clickhouse-native-client 0.1.0

Async ClickHouse client using the native TCP protocol with LZ4/ZSTD compression and TLS support
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
//! Enum8 and Enum16 column implementations.
//!
//! ClickHouse enums map string names to integer values. `Enum8` uses `Int8`
//! storage (up to 127 distinct values) and `Enum16` uses `Int16` storage
//! (up to 32767 distinct values). The name-to-value mapping is stored in
//! the column's [`Type`].

use super::{
    Column,
    ColumnRef,
};
use crate::{
    types::Type,
    Error,
    Result,
};
use bytes::BytesMut;
use std::sync::Arc;

/// Column for Enum8 type (stored as Int8 with name-value mapping in Type).
pub struct ColumnEnum8 {
    type_: Type,
    data: Vec<i8>,
}

impl ColumnEnum8 {
    /// Create a new empty Enum8 column.
    ///
    /// # Panics
    ///
    /// Panics if `type_` is not `Type::Enum8`.
    pub fn new(type_: Type) -> Self {
        match &type_ {
            Type::Enum8 { .. } => Self { type_, data: Vec::new() },
            _ => panic!("ColumnEnum8 requires Enum8 type"),
        }
    }

    /// Set the column data from a vector of raw `i8` enum values.
    pub fn with_data(mut self, data: Vec<i8>) -> Self {
        self.data = data;
        self
    }

    /// Append enum by numeric value
    pub fn append_value(&mut self, value: i8) {
        self.data.push(value);
    }

    /// Append enum by name (looks up value in Type).
    ///
    /// # Errors
    ///
    /// Returns an error if `name` is not a known variant in this enum type.
    pub fn append_name(&mut self, name: &str) -> Result<()> {
        let value = self.type_.get_enum_value(name).ok_or_else(|| {
            Error::Protocol(format!("Unknown enum name: {}", name))
        })?;

        self.data.push(value as i8);
        Ok(())
    }

    /// Get numeric value at index.
    pub fn at(&self, index: usize) -> i8 {
        self.data[index]
    }

    /// Get enum name at index (looks up in Type).
    pub fn name_at(&self, index: usize) -> Option<&str> {
        let value = self.data[index] as i16;
        self.type_.get_enum_name(value)
    }

    /// Returns the number of values in this column.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns `true` if the column contains no values.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
}

impl Column for ColumnEnum8 {
    fn column_type(&self) -> &Type {
        &self.type_
    }

    fn size(&self) -> usize {
        self.data.len()
    }

    fn clear(&mut self) {
        self.data.clear();
    }

    fn reserve(&mut self, new_cap: usize) {
        self.data.reserve(new_cap);
    }

    fn append_column(&mut self, other: ColumnRef) -> Result<()> {
        let other =
            other.as_any().downcast_ref::<ColumnEnum8>().ok_or_else(|| {
                Error::TypeMismatch {
                    expected: self.type_.name(),
                    actual: other.column_type().name(),
                }
            })?;

        self.data.extend_from_slice(&other.data);
        Ok(())
    }

    fn load_from_buffer(
        &mut self,
        buffer: &mut &[u8],
        rows: usize,
    ) -> Result<()> {
        let bytes_needed = rows;
        if buffer.len() < bytes_needed {
            return Err(Error::Protocol(format!(
                "Buffer underflow: need {} bytes for Enum8, have {}",
                bytes_needed,
                buffer.len()
            )));
        }

        // Use bulk copy for performance
        self.data.reserve(rows);
        let current_len = self.data.len();
        unsafe {
            // Set length first to claim ownership of the memory
            self.data.set_len(current_len + rows);
            let dest_ptr =
                (self.data.as_mut_ptr() as *mut u8).add(current_len);
            std::ptr::copy_nonoverlapping(
                buffer.as_ptr(),
                dest_ptr,
                bytes_needed,
            );
        }

        use bytes::Buf;
        buffer.advance(bytes_needed);
        Ok(())
    }

    fn save_to_buffer(&self, buffer: &mut BytesMut) -> Result<()> {
        if !self.data.is_empty() {
            let byte_slice = unsafe {
                std::slice::from_raw_parts(
                    self.data.as_ptr() as *const u8,
                    self.data.len(),
                )
            };
            buffer.extend_from_slice(byte_slice);
        }
        Ok(())
    }

    fn clone_empty(&self) -> ColumnRef {
        Arc::new(ColumnEnum8::new(self.type_.clone()))
    }

    fn slice(&self, begin: usize, len: usize) -> Result<ColumnRef> {
        if begin + len > self.data.len() {
            return Err(Error::InvalidArgument(format!(
                "Slice out of bounds: begin={}, len={}, size={}",
                begin,
                len,
                self.data.len()
            )));
        }

        let sliced_data = self.data[begin..begin + len].to_vec();
        Ok(Arc::new(
            ColumnEnum8::new(self.type_.clone()).with_data(sliced_data),
        ))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

/// Column for Enum16 type (stored as Int16 with name-value mapping in Type).
pub struct ColumnEnum16 {
    type_: Type,
    data: Vec<i16>,
}

impl ColumnEnum16 {
    /// Create a new empty Enum16 column.
    ///
    /// # Panics
    ///
    /// Panics if `type_` is not `Type::Enum16`.
    pub fn new(type_: Type) -> Self {
        match &type_ {
            Type::Enum16 { .. } => Self { type_, data: Vec::new() },
            _ => panic!("ColumnEnum16 requires Enum16 type"),
        }
    }

    /// Set the column data from a vector of raw `i16` enum values.
    pub fn with_data(mut self, data: Vec<i16>) -> Self {
        self.data = data;
        self
    }

    /// Append enum by numeric value.
    pub fn append_value(&mut self, value: i16) {
        self.data.push(value);
    }

    /// Append enum by name (looks up value in Type).
    ///
    /// # Errors
    ///
    /// Returns an error if `name` is not a known variant in this enum type.
    pub fn append_name(&mut self, name: &str) -> Result<()> {
        let value = self.type_.get_enum_value(name).ok_or_else(|| {
            Error::Protocol(format!("Unknown enum name: {}", name))
        })?;

        self.data.push(value);
        Ok(())
    }

    /// Get numeric value at index.
    pub fn at(&self, index: usize) -> i16 {
        self.data[index]
    }

    /// Get enum name at index (looks up in Type).
    pub fn name_at(&self, index: usize) -> Option<&str> {
        let value = self.data[index];
        self.type_.get_enum_name(value)
    }

    /// Returns the number of values in this column.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns `true` if the column contains no values.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
}

impl Column for ColumnEnum16 {
    fn column_type(&self) -> &Type {
        &self.type_
    }

    fn size(&self) -> usize {
        self.data.len()
    }

    fn clear(&mut self) {
        self.data.clear();
    }

    fn reserve(&mut self, new_cap: usize) {
        self.data.reserve(new_cap);
    }

    fn append_column(&mut self, other: ColumnRef) -> Result<()> {
        let other = other.as_any().downcast_ref::<ColumnEnum16>().ok_or_else(
            || Error::TypeMismatch {
                expected: self.type_.name(),
                actual: other.column_type().name(),
            },
        )?;

        self.data.extend_from_slice(&other.data);
        Ok(())
    }

    fn load_from_buffer(
        &mut self,
        buffer: &mut &[u8],
        rows: usize,
    ) -> Result<()> {
        let bytes_needed = rows * 2;
        if buffer.len() < bytes_needed {
            return Err(Error::Protocol(format!(
                "Buffer underflow: need {} bytes for Enum16, have {}",
                bytes_needed,
                buffer.len()
            )));
        }

        // Use bulk copy for performance
        self.data.reserve(rows);
        let current_len = self.data.len();
        unsafe {
            // Set length first to claim ownership of the memory
            self.data.set_len(current_len + rows);
            let dest_ptr =
                (self.data.as_mut_ptr() as *mut u8).add(current_len * 2);
            std::ptr::copy_nonoverlapping(
                buffer.as_ptr(),
                dest_ptr,
                bytes_needed,
            );
        }

        use bytes::Buf;
        buffer.advance(bytes_needed);
        Ok(())
    }

    fn save_to_buffer(&self, buffer: &mut BytesMut) -> Result<()> {
        if !self.data.is_empty() {
            let byte_slice = unsafe {
                std::slice::from_raw_parts(
                    self.data.as_ptr() as *const u8,
                    self.data.len() * 2,
                )
            };
            buffer.extend_from_slice(byte_slice);
        }
        Ok(())
    }

    fn clone_empty(&self) -> ColumnRef {
        Arc::new(ColumnEnum16::new(self.type_.clone()))
    }

    fn slice(&self, begin: usize, len: usize) -> Result<ColumnRef> {
        if begin + len > self.data.len() {
            return Err(Error::InvalidArgument(format!(
                "Slice out of bounds: begin={}, len={}, size={}",
                begin,
                len,
                self.data.len()
            )));
        }

        let sliced_data = self.data[begin..begin + len].to_vec();
        Ok(Arc::new(
            ColumnEnum16::new(self.type_.clone()).with_data(sliced_data),
        ))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;
    use crate::types::EnumItem;

    #[test]
    fn test_enum8_append_value() {
        let items = vec![
            EnumItem { name: "Red".to_string(), value: 1 },
            EnumItem { name: "Green".to_string(), value: 2 },
        ];
        let mut col = ColumnEnum8::new(Type::enum8(items));

        col.append_value(1);
        col.append_value(2);

        assert_eq!(col.len(), 2);
        assert_eq!(col.at(0), 1);
        assert_eq!(col.at(1), 2);
    }

    #[test]
    fn test_enum8_append_name() {
        let items = vec![
            EnumItem { name: "Red".to_string(), value: 1 },
            EnumItem { name: "Green".to_string(), value: 2 },
        ];
        let mut col = ColumnEnum8::new(Type::enum8(items));

        col.append_name("Red").unwrap();
        col.append_name("Green").unwrap();

        assert_eq!(col.len(), 2);
        assert_eq!(col.at(0), 1);
        assert_eq!(col.at(1), 2);
        assert_eq!(col.name_at(0), Some("Red"));
        assert_eq!(col.name_at(1), Some("Green"));
    }

    #[test]
    fn test_enum16() {
        let items = vec![
            EnumItem { name: "Small".to_string(), value: 100 },
            EnumItem { name: "Large".to_string(), value: 1000 },
        ];
        let mut col = ColumnEnum16::new(Type::enum16(items));

        col.append_value(100);
        col.append_name("Large").unwrap();

        assert_eq!(col.len(), 2);
        assert_eq!(col.at(0), 100);
        assert_eq!(col.at(1), 1000);
        assert_eq!(col.name_at(0), Some("Small"));
        assert_eq!(col.name_at(1), Some("Large"));
    }
}