Skip to main content

connectorx/sources/clickhouse/
mod.rs

1//! Source implementation for ClickHouse using the native protocol.
2
3mod errors;
4mod typesystem;
5
6pub use self::errors::ClickHouseSourceError;
7pub use self::typesystem::{ClickHouseTypeSystem, TypeMetadata};
8
9use crate::{
10    data_order::DataOrder,
11    errors::ConnectorXError,
12    sources::{
13        clickhouse::typesystem::DataType, PartitionParser, Produce, Source, SourcePartition,
14    },
15    sql::{count_query, limit0_query, CXQuery},
16};
17use anyhow::anyhow;
18use chrono::{DateTime, Duration, NaiveDate, NaiveTime, Utc};
19use chrono_tz::Tz;
20use clickhouse::Client;
21use fehler::{throw, throws};
22use rust_decimal::Decimal;
23use serde::Deserialize;
24use serde_json::Value as JsonValue;
25use sqlparser::dialect::{ClickHouseDialect, GenericDialect};
26use std::io::{Cursor, Read};
27use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
28use std::sync::Arc;
29use tokio::runtime::Runtime;
30use uuid::Uuid;
31
32/// ClickHouse source that uses the HTTP protocol.
33pub struct ClickHouseSource {
34    rt: Arc<Runtime>,
35    /// HTTP client connected to the server.
36    pub client: Client,
37    origin_query: Option<String>,
38    queries: Vec<CXQuery<String>>,
39    names: Vec<String>,
40    schema: Vec<ClickHouseTypeSystem>,
41    metadata: Vec<TypeMetadata>,
42}
43
44impl ClickHouseSource {
45    /// Connect to the server given by a `clickhouse://` URL (`protocol=https` selects HTTPS).
46    #[throws(ClickHouseSourceError)]
47    pub fn new(rt: Arc<Runtime>, conn: &str) -> Self {
48        let url = url::Url::parse(conn)?;
49
50        let use_https = url
51            .query_pairs()
52            .find(|(k, v)| k == "protocol" && v == "https")
53            .is_some();
54
55        let base_url = format!(
56            "{}://{}:{}",
57            if use_https { "https" } else { "http" },
58            url.host_str().unwrap_or("localhost"),
59            url.port().unwrap_or(8123)
60        );
61
62        // Only the client's `lz4` feature is enabled, so it decodes LZ4 only;
63        // newer servers default to ZSTD.
64        let mut client = Client::default()
65            .with_url(&base_url)
66            .with_setting("network_compression_method", "lz4");
67
68        let database = url.path().trim_start_matches('/');
69        if !database.is_empty() {
70            client = client.with_database(database);
71        }
72
73        let username = url.username();
74        if !username.is_empty() {
75            client = client.with_user(username);
76        }
77
78        let password = url.password().unwrap_or("");
79        if !password.is_empty() {
80            client = client.with_password(password);
81        }
82
83        Self {
84            rt,
85            client,
86            origin_query: None,
87            queries: vec![],
88            names: vec![],
89            schema: vec![],
90            metadata: vec![],
91        }
92    }
93}
94
95impl Source for ClickHouseSource
96where
97    ClickHouseSourcePartition:
98        SourcePartition<TypeSystem = ClickHouseTypeSystem, Error = ClickHouseSourceError>,
99{
100    const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::RowMajor];
101    type Partition = ClickHouseSourcePartition;
102    type TypeSystem = ClickHouseTypeSystem;
103    type Error = ClickHouseSourceError;
104
105    #[throws(ClickHouseSourceError)]
106    fn set_data_order(&mut self, data_order: DataOrder) {
107        if !matches!(data_order, DataOrder::RowMajor) {
108            throw!(ConnectorXError::UnsupportedDataOrder(data_order));
109        }
110    }
111
112    fn set_queries<Q: ToString>(&mut self, queries: &[CXQuery<Q>]) {
113        self.queries = queries.iter().map(|q| q.map(Q::to_string)).collect();
114    }
115
116    fn set_origin_query(&mut self, query: Option<String>) {
117        self.origin_query = query;
118    }
119
120    #[throws(ClickHouseSourceError)]
121    fn fetch_metadata(&mut self) {
122        assert!(!self.queries.is_empty());
123
124        let first_query = &self.queries[0];
125        let l1query = limit0_query(first_query, &ClickHouseDialect {})?;
126
127        let describe_query = format!("DESCRIBE ({})", l1query.as_str());
128
129        let response = self.rt.block_on(async {
130            let mut cursor = self
131                .client
132                .query(&describe_query)
133                .fetch_bytes("JSONCompact")
134                .map_err(|e| anyhow!("ClickHouse error: {}", e))?;
135            let bytes = cursor
136                .collect()
137                .await
138                .map_err(|e| anyhow!("ClickHouse error: {}", e))?;
139            Ok::<_, ClickHouseSourceError>(bytes)
140        })?;
141
142        #[derive(Debug, Deserialize)]
143        struct DescribeResponse {
144            data: Vec<Vec<JsonValue>>,
145        }
146
147        let parsed: DescribeResponse = serde_json::from_slice(&response)
148            .map_err(|e| anyhow!("Failed to parse DESCRIBE response: {}", e))?;
149
150        let mut names = Vec::new();
151        let mut types = Vec::new();
152        let mut metadata = Vec::new();
153
154        for row in parsed.data {
155            if row.len() >= 2 {
156                let name = row[0].as_str().unwrap_or("").to_string();
157                let type_str = row[1].as_str().unwrap_or("String");
158                let (ts, meta) = ClickHouseTypeSystem::from_type_str_with_metadata(type_str);
159                names.push(name);
160                types.push(ts);
161                metadata.push(meta);
162            }
163        }
164
165        self.names = names;
166        self.schema = types;
167        self.metadata = metadata;
168    }
169
170    #[throws(ClickHouseSourceError)]
171    fn result_rows(&mut self) -> Option<usize> {
172        match &self.origin_query {
173            Some(q) => {
174                let cxq = CXQuery::Naked(q.clone());
175                let cquery = count_query(&cxq, &ClickHouseDialect {})?;
176
177                let response = self.rt.block_on(async {
178                    let mut cursor = self
179                        .client
180                        .query(cquery.as_str())
181                        .fetch_bytes("JSONCompact")
182                        .map_err(|e| anyhow!("ClickHouse error: {}", e))?;
183                    let bytes = cursor
184                        .collect()
185                        .await
186                        .map_err(|e| anyhow!("ClickHouse error: {}", e))?;
187                    Ok::<_, ClickHouseSourceError>(bytes)
188                })?;
189
190                #[derive(Debug, Deserialize)]
191                struct CountResponse {
192                    data: Vec<Vec<JsonValue>>,
193                }
194
195                let parsed: CountResponse = serde_json::from_slice(&response)
196                    .map_err(|e| anyhow!("Failed to parse count response: {}", e))?;
197
198                if let Some(row) = parsed.data.first() {
199                    if let Some(count_val) = row.first() {
200                        let count = match count_val {
201                            JsonValue::Number(n) => n.as_u64().unwrap_or(0),
202                            JsonValue::String(s) => s.parse().unwrap_or(0),
203                            _ => 0,
204                        };
205                        return Some(count as usize);
206                    }
207                }
208                None
209            }
210            None => None,
211        }
212    }
213
214    fn names(&self) -> Vec<String> {
215        self.names.clone()
216    }
217
218    fn schema(&self) -> Vec<Self::TypeSystem> {
219        self.schema.clone()
220    }
221
222    #[throws(ClickHouseSourceError)]
223    fn partition(self) -> Vec<Self::Partition> {
224        let mut ret = vec![];
225        for query in self.queries {
226            ret.push(ClickHouseSourcePartition::new(
227                self.rt.clone(),
228                self.client.clone(),
229                &query,
230                &self.schema,
231                &self.metadata,
232            ));
233        }
234        ret
235    }
236}
237
238/// One partition of a [`ClickHouseSource`].
239pub struct ClickHouseSourcePartition {
240    rt: Arc<Runtime>,
241    client: Client,
242    query: CXQuery<String>,
243    schema: Vec<ClickHouseTypeSystem>,
244    metadata: Vec<TypeMetadata>,
245    nrows: usize,
246    ncols: usize,
247}
248
249impl ClickHouseSourcePartition {
250    /// Create a partition that runs `query`.
251    pub fn new(
252        rt: Arc<Runtime>,
253        client: Client,
254        query: &CXQuery<String>,
255        schema: &[ClickHouseTypeSystem],
256        metadata: &[TypeMetadata],
257    ) -> Self {
258        Self {
259            rt,
260            client,
261            query: query.clone(),
262            schema: schema.to_vec(),
263            metadata: metadata.to_vec(),
264            nrows: 0,
265            ncols: schema.len(),
266        }
267    }
268}
269
270impl SourcePartition for ClickHouseSourcePartition {
271    type TypeSystem = ClickHouseTypeSystem;
272    type Parser<'a> = ClickHouseSourceParser<'a>;
273    type Error = ClickHouseSourceError;
274
275    #[throws(ClickHouseSourceError)]
276    fn result_rows(&mut self) {
277        let cquery = count_query(&self.query, &GenericDialect {})?;
278
279        let response = self.rt.block_on(async {
280            let mut cursor = self
281                .client
282                .query(cquery.as_str())
283                .fetch_bytes("JSONCompact")
284                .map_err(|e| anyhow!("ClickHouse error: {}", e))?;
285            let bytes = cursor
286                .collect()
287                .await
288                .map_err(|e| anyhow!("ClickHouse error: {}", e))?;
289            Ok::<_, ClickHouseSourceError>(bytes)
290        })?;
291
292        #[derive(Debug, Deserialize)]
293        struct CountResponse {
294            data: Vec<Vec<JsonValue>>,
295        }
296
297        let parsed: CountResponse = serde_json::from_slice(&response)
298            .map_err(|e| anyhow!("Failed to parse count response: {}", e))?;
299
300        if let Some(row) = parsed.data.first() {
301            if let Some(count_val) = row.first() {
302                let count = match count_val {
303                    JsonValue::Number(n) => n.as_u64().unwrap_or(0),
304                    JsonValue::String(s) => s.parse().unwrap_or(0),
305                    _ => 0,
306                };
307                self.nrows = count as usize;
308            }
309        }
310    }
311
312    #[throws(ClickHouseSourceError)]
313    fn parser(&mut self) -> Self::Parser<'_> {
314        ClickHouseSourceParser::new(
315            self.rt.clone(),
316            self.client.clone(),
317            self.query.clone(),
318            &self.schema,
319            &self.metadata,
320        )?
321    }
322
323    fn nrows(&self) -> usize {
324        self.nrows
325    }
326
327    fn ncols(&self) -> usize {
328        self.ncols
329    }
330}
331
332struct BinaryReader<'a> {
333    cursor: Cursor<&'a [u8]>,
334}
335
336impl<'a> BinaryReader<'a> {
337    fn new(data: &'a [u8]) -> Self {
338        Self {
339            cursor: Cursor::new(data),
340        }
341    }
342
343    fn read_bytes<const N: usize>(&mut self) -> Result<[u8; N], ClickHouseSourceError> {
344        let mut buf = [0u8; N];
345        self.cursor
346            .read_exact(&mut buf)
347            .map_err(|e| anyhow!("Failed to read {} bytes: {}", N, e))?;
348        Ok(buf)
349    }
350
351    fn read_u8(&mut self) -> Result<u8, ClickHouseSourceError> {
352        Ok(self.read_bytes::<1>()?[0])
353    }
354
355    fn read_i8(&mut self) -> Result<i8, ClickHouseSourceError> {
356        Ok(self.read_u8()? as i8)
357    }
358
359    fn read_u16(&mut self) -> Result<u16, ClickHouseSourceError> {
360        Ok(u16::from_le_bytes(self.read_bytes()?))
361    }
362
363    fn read_i16(&mut self) -> Result<i16, ClickHouseSourceError> {
364        Ok(i16::from_le_bytes(self.read_bytes()?))
365    }
366
367    fn read_u32(&mut self) -> Result<u32, ClickHouseSourceError> {
368        Ok(u32::from_le_bytes(self.read_bytes()?))
369    }
370
371    fn read_i32(&mut self) -> Result<i32, ClickHouseSourceError> {
372        Ok(i32::from_le_bytes(self.read_bytes()?))
373    }
374
375    fn read_u64(&mut self) -> Result<u64, ClickHouseSourceError> {
376        Ok(u64::from_le_bytes(self.read_bytes()?))
377    }
378
379    fn read_i64(&mut self) -> Result<i64, ClickHouseSourceError> {
380        Ok(i64::from_le_bytes(self.read_bytes()?))
381    }
382
383    fn read_f32(&mut self) -> Result<f32, ClickHouseSourceError> {
384        Ok(f32::from_le_bytes(self.read_bytes()?))
385    }
386
387    fn read_f64(&mut self) -> Result<f64, ClickHouseSourceError> {
388        Ok(f64::from_le_bytes(self.read_bytes()?))
389    }
390
391    fn read_varint(&mut self) -> Result<u64, ClickHouseSourceError> {
392        let mut result: u64 = 0;
393        let mut shift = 0;
394        loop {
395            let byte = self.read_u8()?;
396            result |= ((byte & 0x7f) as u64) << shift;
397            if byte & 0x80 == 0 {
398                break;
399            }
400            shift += 7;
401            if shift >= 64 {
402                return Err(anyhow!("Varint too long").into());
403            }
404        }
405        Ok(result)
406    }
407
408    fn read_fixed_string(&mut self, len: usize) -> Result<Vec<u8>, ClickHouseSourceError> {
409        let mut buf = vec![0u8; len];
410        self.cursor
411            .read_exact(&mut buf)
412            .map_err(|e| anyhow!("Failed to read FixedString: {}", e))?;
413        Ok(buf)
414    }
415
416    fn read_string(&mut self) -> Result<String, ClickHouseSourceError> {
417        let len = self.read_varint()? as usize;
418        let mut buf = vec![0u8; len];
419        self.cursor
420            .read_exact(&mut buf)
421            .map_err(|e| anyhow!("Failed to read string: {}", e))?;
422        String::from_utf8(buf).map_err(|e| anyhow!("Invalid UTF-8: {}", e).into())
423    }
424
425    fn read_uuid(&mut self) -> Result<Uuid, ClickHouseSourceError> {
426        // ClickHouse stores UUID as two UInt64 in big-endian order
427        let high = self.read_u64()?;
428        let low = self.read_u64()?;
429
430        Ok(Uuid::from_u64_pair(high, low))
431    }
432
433    fn read_bool(&mut self) -> Result<bool, ClickHouseSourceError> {
434        Ok(self.read_u8()? != 0)
435    }
436
437    fn read_date(&mut self) -> Result<NaiveDate, ClickHouseSourceError> {
438        // ClickHouse stores Date as UInt16 representing days since 1970-01-01
439        let days = self.read_u16()? as i64;
440        let epoch = NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
441        epoch
442            .checked_add_signed(Duration::days(days))
443            .ok_or_else(|| anyhow!("Invalid date value: {} days since epoch", days).into())
444    }
445
446    fn read_date32(&mut self) -> Result<NaiveDate, ClickHouseSourceError> {
447        // ClickHouse stores Date32 as Int32 representing days since 1970-01-01
448        // negative values represent dates before 1970-01-01
449        let days = self.read_i32()? as i64;
450        let epoch = NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
451        epoch
452            .checked_add_signed(Duration::days(days))
453            .ok_or_else(|| anyhow!("Invalid date32 value: {} days since epoch", days).into())
454    }
455
456    fn read_datetime(&mut self, tz: Option<&Tz>) -> Result<DateTime<Utc>, ClickHouseSourceError> {
457        let seconds = self.read_u32()? as i64;
458        chrono::DateTime::from_timestamp(seconds, 0)
459            .map(|dt| dt.with_timezone(tz.unwrap_or(&Tz::UTC)).to_utc())
460            .ok_or_else(|| {
461                anyhow!("Invalid datetime value: {} seconds since epoch", seconds).into()
462            })
463    }
464
465    fn read_datetime64(
466        &mut self,
467        precision: u8,
468        tz: Option<&Tz>,
469    ) -> Result<DateTime<Utc>, ClickHouseSourceError> {
470        if precision > 9 {
471            return Err(anyhow!("Unsupported DateTime64 precision: {}", precision).into());
472        }
473        let ticks = self.read_i64()?;
474        let scale = 10_i64.pow(precision as u32);
475        let seconds = ticks.div_euclid(scale);
476        let fractional_ticks = ticks.rem_euclid(scale) as u32;
477        let nanos = fractional_ticks * 10_u32.pow(9 - precision as u32);
478
479        DateTime::from_timestamp(seconds, nanos)
480            .map(|dt| dt.with_timezone(tz.unwrap_or(&Tz::UTC)).to_utc())
481            .ok_or_else(|| anyhow!("Invalid datetime64 value: {} ticks", ticks).into())
482    }
483
484    fn read_decimal(&mut self, precision: u8, scale: u8) -> Result<Decimal, ClickHouseSourceError> {
485        match precision {
486            1..=9 => {
487                let value = self.read_i32()?;
488                Ok(Decimal::new(value as i64, scale as u32))
489            }
490            10..=18 => {
491                let value = self.read_i64()?;
492                Ok(Decimal::new(value, scale as u32))
493            }
494            _ => Err(anyhow!("Unsupported Decimal precision: {}", precision).into()),
495        }
496    }
497
498    fn read_time(&mut self) -> Result<NaiveTime, ClickHouseSourceError> {
499        let seconds = self.read_u32()? as i64;
500        Ok(
501            NaiveTime::from_num_seconds_from_midnight_opt(seconds as u32, 0)
502                .ok_or_else(|| anyhow!("Invalid time value: {} seconds since midnight", seconds))?,
503        )
504    }
505
506    fn read_time64(&mut self, precision: u8) -> Result<NaiveTime, ClickHouseSourceError> {
507        if precision > 9 {
508            return Err(anyhow!("Unsupported Time64 precision: {}", precision).into());
509        }
510        let ticks = self.read_i64()?;
511        let nanos = ticks * 10_i64.pow(9 - precision as u32);
512        Ok(NaiveTime::from_num_seconds_from_midnight_opt(
513            (nanos / 1_000_000_000) as u32,
514            (nanos % 1_000_000_000) as u32,
515        )
516        .ok_or_else(|| anyhow!("Invalid time64 value: {} ticks since midnight", ticks))?)
517    }
518
519    fn read_ipv4(&mut self) -> Result<IpAddr, ClickHouseSourceError> {
520        let bytes = self.read_u32()?;
521
522        Ok(IpAddr::V4(Ipv4Addr::from_bits(bytes)))
523    }
524
525    fn read_ipv6(&mut self) -> Result<IpAddr, ClickHouseSourceError> {
526        let seg1 = u16::from_be(self.read_u16()?);
527        let seg2 = u16::from_be(self.read_u16()?);
528        let seg3 = u16::from_be(self.read_u16()?);
529        let seg4 = u16::from_be(self.read_u16()?);
530        let seg5 = u16::from_be(self.read_u16()?);
531        let seg6 = u16::from_be(self.read_u16()?);
532        let seg7 = u16::from_be(self.read_u16()?);
533        let seg8 = u16::from_be(self.read_u16()?);
534
535        Ok(IpAddr::V6(Ipv6Addr::from_segments([
536            seg1, seg2, seg3, seg4, seg5, seg6, seg7, seg8,
537        ])))
538    }
539
540    fn read_enum8(&mut self) -> Result<i8, ClickHouseSourceError> {
541        self.read_i8()
542    }
543
544    fn read_enum16(&mut self) -> Result<i16, ClickHouseSourceError> {
545        self.read_i16()
546    }
547
548    fn read_array<T, F>(&mut self, read_elem: F) -> Result<Vec<Option<T>>, ClickHouseSourceError>
549    where
550        F: Fn(&mut Self) -> Result<T, ClickHouseSourceError>,
551    {
552        let len = self.read_varint()? as usize;
553        let mut result = Vec::with_capacity(len);
554        for _ in 0..len {
555            result.push(Some(read_elem(self)?));
556        }
557        Ok(result)
558    }
559
560    fn is_empty(&self) -> bool {
561        self.cursor.position() as usize >= self.cursor.get_ref().len()
562    }
563}
564
565/// Row parser for a ClickHouse partition.
566pub struct ClickHouseSourceParser<'a> {
567    rt: Arc<Runtime>,
568    client: Client,
569    query: CXQuery<String>,
570    schema: Vec<ClickHouseTypeSystem>,
571    metadata: Vec<TypeMetadata>,
572    rowbuf: Vec<Vec<DataType>>,
573    ncols: usize,
574    current_row: usize,
575    current_col: usize,
576    is_finished: bool,
577    _phantom: std::marker::PhantomData<&'a ()>,
578}
579
580impl<'a> ClickHouseSourceParser<'a> {
581    /// Run `query` and prepare to parse its rows.
582    #[throws(ClickHouseSourceError)]
583    pub fn new(
584        rt: Arc<Runtime>,
585        client: Client,
586        query: CXQuery<String>,
587        schema: &[ClickHouseTypeSystem],
588        metadata: &[TypeMetadata],
589    ) -> Self {
590        Self {
591            rt,
592            client,
593            query,
594            schema: schema.to_vec(),
595            metadata: metadata.to_vec(),
596            rowbuf: Vec::new(),
597            ncols: schema.len(),
598            current_row: 0,
599            current_col: 0,
600            is_finished: false,
601            _phantom: std::marker::PhantomData,
602        }
603    }
604
605    fn parse_row_binary(
606        &self,
607        reader: &mut BinaryReader,
608    ) -> Result<Vec<DataType>, ClickHouseSourceError> {
609        let mut row = Vec::with_capacity(self.ncols);
610
611        for (col_idx, col_type) in self.schema.iter().enumerate() {
612            let is_nullable = col_type.is_nullable();
613            let meta = &self.metadata[col_idx];
614
615            if is_nullable {
616                let null_flag = reader.read_u8()?;
617                if null_flag == 1 {
618                    row.push(DataType::Null);
619                    continue;
620                }
621            }
622
623            let value = match col_type {
624                ClickHouseTypeSystem::Int8(_) => DataType::Int8(reader.read_i8()?),
625                ClickHouseTypeSystem::Int16(_) => DataType::Int16(reader.read_i16()?),
626                ClickHouseTypeSystem::Int32(_) => DataType::Int32(reader.read_i32()?),
627                ClickHouseTypeSystem::Int64(_) => DataType::Int64(reader.read_i64()?),
628                ClickHouseTypeSystem::UInt8(_) => DataType::UInt8(reader.read_u8()?),
629                ClickHouseTypeSystem::UInt16(_) => DataType::UInt16(reader.read_u16()?),
630                ClickHouseTypeSystem::UInt32(_) => DataType::UInt32(reader.read_u32()?),
631                ClickHouseTypeSystem::UInt64(_) => DataType::UInt64(reader.read_u64()?),
632
633                ClickHouseTypeSystem::Float32(_) => DataType::Float32(reader.read_f32()?),
634                ClickHouseTypeSystem::Float64(_) => DataType::Float64(reader.read_f64()?),
635
636                ClickHouseTypeSystem::Decimal(_) => {
637                    DataType::Decimal(reader.read_decimal(meta.precision, meta.scale)?)
638                }
639
640                ClickHouseTypeSystem::String(_) => DataType::String(reader.read_string()?),
641
642                ClickHouseTypeSystem::FixedString(_) => {
643                    DataType::FixedString(reader.read_fixed_string(meta.length)?)
644                }
645
646                ClickHouseTypeSystem::Date(_) => DataType::Date(reader.read_date()?),
647                ClickHouseTypeSystem::Date32(_) => DataType::Date32(reader.read_date32()?),
648
649                ClickHouseTypeSystem::DateTime(_) => {
650                    DataType::DateTime(reader.read_datetime(meta.timezone.as_ref())?)
651                }
652                ClickHouseTypeSystem::DateTime64(_) => DataType::DateTime64(
653                    reader.read_datetime64(meta.precision, meta.timezone.as_ref())?,
654                ),
655
656                ClickHouseTypeSystem::Time(_) => DataType::Time(reader.read_time()?),
657                ClickHouseTypeSystem::Time64(_) => {
658                    DataType::Time64(reader.read_time64(meta.precision)?)
659                }
660
661                ClickHouseTypeSystem::Enum8(_) => {
662                    let enum_value = reader.read_enum8()?;
663                    let enum_str = meta
664                        .named_values
665                        .as_ref()
666                        .and_then(|h| h.get(&(enum_value as i16)));
667                    DataType::Enum8(enum_str.cloned().unwrap_or_default())
668                }
669                ClickHouseTypeSystem::Enum16(_) => {
670                    let enum_value = reader.read_enum16()?;
671                    let enum_str = meta.named_values.as_ref().and_then(|h| h.get(&enum_value));
672                    DataType::Enum16(enum_str.cloned().unwrap_or_default())
673                }
674
675                ClickHouseTypeSystem::UUID(_) => DataType::UUID(reader.read_uuid()?),
676
677                ClickHouseTypeSystem::IPv4(_) => DataType::IPv4(reader.read_ipv4()?),
678                ClickHouseTypeSystem::IPv6(_) => DataType::IPv6(reader.read_ipv6()?),
679
680                ClickHouseTypeSystem::Bool(_) => DataType::Bool(reader.read_bool()?),
681
682                ClickHouseTypeSystem::ArrayBool(_) => {
683                    DataType::ArrayBool(reader.read_array(BinaryReader::read_bool)?)
684                }
685                ClickHouseTypeSystem::ArrayString(_) => {
686                    DataType::ArrayString(reader.read_array(BinaryReader::read_string)?)
687                }
688                ClickHouseTypeSystem::ArrayInt8(_) => {
689                    DataType::ArrayInt8(reader.read_array(BinaryReader::read_i8)?)
690                }
691                ClickHouseTypeSystem::ArrayInt16(_) => {
692                    DataType::ArrayInt16(reader.read_array(BinaryReader::read_i16)?)
693                }
694                ClickHouseTypeSystem::ArrayInt32(_) => {
695                    DataType::ArrayInt32(reader.read_array(BinaryReader::read_i32)?)
696                }
697                ClickHouseTypeSystem::ArrayInt64(_) => {
698                    DataType::ArrayInt64(reader.read_array(BinaryReader::read_i64)?)
699                }
700                ClickHouseTypeSystem::ArrayUInt8(_) => {
701                    DataType::ArrayUInt8(reader.read_array(BinaryReader::read_u8)?)
702                }
703                ClickHouseTypeSystem::ArrayUInt16(_) => {
704                    DataType::ArrayUInt16(reader.read_array(BinaryReader::read_u16)?)
705                }
706                ClickHouseTypeSystem::ArrayUInt32(_) => {
707                    DataType::ArrayUInt32(reader.read_array(BinaryReader::read_u32)?)
708                }
709                ClickHouseTypeSystem::ArrayUInt64(_) => {
710                    DataType::ArrayUInt64(reader.read_array(BinaryReader::read_u64)?)
711                }
712                ClickHouseTypeSystem::ArrayFloat32(_) => {
713                    DataType::ArrayFloat32(reader.read_array(BinaryReader::read_f32)?)
714                }
715                ClickHouseTypeSystem::ArrayFloat64(_) => {
716                    DataType::ArrayFloat64(reader.read_array(BinaryReader::read_f64)?)
717                }
718                ClickHouseTypeSystem::ArrayDecimal(_) => {
719                    let precision = meta.precision;
720                    let scale = meta.scale;
721                    DataType::ArrayDecimal(reader.read_array(|r| r.read_decimal(precision, scale))?)
722                }
723            };
724
725            row.push(value);
726        }
727
728        Ok(row)
729    }
730
731    #[throws(ClickHouseSourceError)]
732    fn next_loc(&mut self) -> (usize, usize) {
733        let ret = (self.current_row, self.current_col);
734        self.current_row += (self.current_col + 1) / self.ncols;
735        self.current_col = (self.current_col + 1) % self.ncols;
736        ret
737    }
738}
739
740impl<'a> PartitionParser<'a> for ClickHouseSourceParser<'a> {
741    type TypeSystem = ClickHouseTypeSystem;
742    type Error = ClickHouseSourceError;
743
744    #[throws(ClickHouseSourceError)]
745    fn fetch_next(&mut self) -> (usize, bool) {
746        assert!(self.current_col == 0);
747
748        if self.is_finished {
749            return (0, true);
750        }
751
752        let response = self.rt.block_on(async {
753            let mut cursor = self
754                .client
755                .query(self.query.as_str())
756                .fetch_bytes("RowBinary")
757                .map_err(|e| anyhow!("ClickHouse error: {}", e))?;
758            let bytes = cursor
759                .collect()
760                .await
761                .map_err(|e| anyhow!("ClickHouse error: {}", e))?;
762            Ok::<_, ClickHouseSourceError>(bytes)
763        })?;
764        let mut reader = BinaryReader::new(&response);
765        let mut rows = Vec::new();
766
767        while !reader.is_empty() {
768            match self.parse_row_binary(&mut reader) {
769                Ok(row) => rows.push(row),
770                Err(_) => break,
771            }
772        }
773
774        self.rowbuf = rows;
775        self.current_row = 0;
776        self.is_finished = true;
777
778        (self.rowbuf.len(), true)
779    }
780}
781
782macro_rules! impl_produce {
783    ($rust_type:ty, [$($variant:ident),+]) => {
784        impl<'r, 'a> Produce<'r, $rust_type> for ClickHouseSourceParser<'a> {
785            type Error = ClickHouseSourceError;
786
787            #[throws(ClickHouseSourceError)]
788            fn produce(&'r mut self) -> $rust_type {
789                let (ridx, cidx) = self.next_loc()?;
790                let value = &self.rowbuf[ridx][cidx];
791
792                match value {
793                    $(DataType::$variant(v) => *v as $rust_type,)+
794                    _ => throw!(ConnectorXError::cannot_produce::<$rust_type>(Some(
795                        format!("{:?}", value)
796                    ))),
797                }
798            }
799        }
800
801        impl<'r, 'a> Produce<'r, Option<$rust_type>> for ClickHouseSourceParser<'a> {
802            type Error = ClickHouseSourceError;
803
804            #[throws(ClickHouseSourceError)]
805            fn produce(&'r mut self) -> Option<$rust_type> {
806                let (ridx, cidx) = self.next_loc()?;
807                let value = &self.rowbuf[ridx][cidx];
808
809                match value {
810                    DataType::Null => None,
811                    $(DataType::$variant(v) => Some(*v as $rust_type),)+
812                    _ => throw!(ConnectorXError::cannot_produce::<$rust_type>(Some(
813                        format!("{:?}", value)
814                    ))),
815                }
816            }
817        }
818    };
819}
820
821macro_rules! impl_produce_with_clone {
822    ($rust_type:ty, [$($variant:ident),+]) => {
823        impl<'r, 'a> Produce<'r, $rust_type> for ClickHouseSourceParser<'a> {
824            type Error = ClickHouseSourceError;
825
826            #[throws(ClickHouseSourceError)]
827            fn produce(&'r mut self) -> $rust_type {
828                let (ridx, cidx) = self.next_loc()?;
829                let value = &self.rowbuf[ridx][cidx];
830
831                match value {
832                    $(DataType::$variant(v) => v.clone() as $rust_type,)+
833                    _ => throw!(ConnectorXError::cannot_produce::<$rust_type>(Some(
834                        format!("{:?}", value)
835                    ))),
836                }
837            }
838        }
839
840        impl<'r, 'a> Produce<'r, Option<$rust_type>> for ClickHouseSourceParser<'a> {
841            type Error = ClickHouseSourceError;
842
843            #[throws(ClickHouseSourceError)]
844            fn produce(&'r mut self) -> Option<$rust_type> {
845                let (ridx, cidx) = self.next_loc()?;
846                let value = &self.rowbuf[ridx][cidx];
847
848                match value {
849                    DataType::Null => None,
850                    $(DataType::$variant(v) => Some(v.clone() as $rust_type),)+
851                    _ => throw!(ConnectorXError::cannot_produce::<$rust_type>(Some(
852                        format!("{:?}", value)
853                    ))),
854                }
855            }
856        }
857    };
858}
859
860macro_rules! impl_produce_vec {
861    ($rust_type:ty, [$($variant:ident),+]) => {
862        impl<'r, 'a> Produce<'r, Vec<Option<$rust_type>>> for ClickHouseSourceParser<'a> {
863            type Error = ClickHouseSourceError;
864
865            #[throws(ClickHouseSourceError)]
866            fn produce(&'r mut self) -> Vec<Option<$rust_type>> {
867                let (ridx, cidx) = self.next_loc()?;
868                let value = &self.rowbuf[ridx][cidx];
869
870                match value {
871                    $(DataType::$variant(v) => v.clone(),)+
872                    _ => throw!(ConnectorXError::cannot_produce::<Vec<Option<$rust_type>>>(Some(
873                        format!("{:?}", value)
874                    ))),
875                }
876            }
877        }
878
879        impl<'r, 'a> Produce<'r, Option<Vec<Option<$rust_type>>>> for ClickHouseSourceParser<'a> {
880            type Error = ClickHouseSourceError;
881
882            #[throws(ClickHouseSourceError)]
883            fn produce(&'r mut self) -> Option<Vec<Option<$rust_type>>> {
884                let (ridx, cidx) = self.next_loc()?;
885                let value = &self.rowbuf[ridx][cidx];
886
887                match value {
888                    DataType::Null => None,
889                    $(DataType::$variant(v) => Some(v.clone()),)+
890                    _ => throw!(ConnectorXError::cannot_produce::<Option<Vec<Option<$rust_type>>>>(Some(
891                        format!("{:?}", value)
892                    ))),
893                }
894            }
895        }
896    };
897}
898
899impl_produce!(i8, [Int8]);
900impl_produce!(i16, [Int16]);
901impl_produce!(i32, [Int32]);
902impl_produce!(i64, [Int64]);
903impl_produce!(u8, [UInt8]);
904impl_produce!(u16, [UInt16]);
905impl_produce!(u32, [UInt32]);
906impl_produce!(u64, [UInt64]);
907impl_produce!(f32, [Float32]);
908impl_produce!(f64, [Float64]);
909impl_produce!(Decimal, [Decimal]);
910impl_produce_with_clone!(String, [String, Enum8, Enum16]);
911impl_produce_with_clone!(Vec<u8>, [FixedString]);
912impl_produce!(NaiveDate, [Date, Date32]);
913impl_produce!(DateTime<Utc>, [DateTime, DateTime64]);
914impl_produce!(NaiveTime, [Time, Time64]);
915impl_produce!(Uuid, [UUID]);
916impl_produce!(IpAddr, [IPv4, IPv6]);
917impl_produce!(bool, [Bool]);
918impl_produce_vec!(bool, [ArrayBool]);
919impl_produce_vec!(String, [ArrayString]);
920impl_produce_vec!(i8, [ArrayInt8]);
921impl_produce_vec!(i16, [ArrayInt16]);
922impl_produce_vec!(i32, [ArrayInt32]);
923impl_produce_vec!(i64, [ArrayInt64]);
924impl_produce_vec!(u8, [ArrayUInt8]);
925impl_produce_vec!(u16, [ArrayUInt16]);
926impl_produce_vec!(u32, [ArrayUInt32]);
927impl_produce_vec!(u64, [ArrayUInt64]);
928impl_produce_vec!(f32, [ArrayFloat32]);
929impl_produce_vec!(f64, [ArrayFloat64]);
930impl_produce_vec!(Decimal, [ArrayDecimal]);