Skip to main content

clickhouse_native_rs/
lib.rs

1//! Asynchronous ClickHouse client for Rust over the native TCP protocol, a maintained
2//! continuation of the clickhouse-rs crate: LZ4 and ZSTD, TLS, a connection pool, and
3//! Variant, Dynamic and JSON columns.
4//!
5#![doc = include_str!("../README.md")]
6#![recursion_limit = "1024"]
7
8#[cfg(all(feature = "tls-native-tls", feature = "tls-rustls"))]
9compile_error!(
10    "tls-native-tls and tls-rustls are mutually exclusive and cannot be enabled together"
11);
12
13use std::{fmt, future::Future, time::Duration};
14
15use futures_util::{
16    future, future::BoxFuture, future::FutureExt, stream, stream::BoxStream, StreamExt,
17};
18use log::{info, warn};
19
20use crate::{
21    binary::protocol,
22    connecting_stream::ConnectingStream,
23    errors::{DriverError, Error, Result},
24    io::ClickhouseTransport,
25    pool::PoolBinding,
26    retry_guard::retry_guard,
27    types::{
28        block::{ChunkIterator, INSERT_BLOCK_SIZE},
29        query_result::stream_blocks::BlockStream,
30        Cmd, Context, IntoOptions, OptionsSource, Packet, Query, QueryResult, SqlType,
31    },
32};
33pub use crate::{
34    errors::ConnectionError,
35    pool::Pool,
36    types::{block::Block, Compression, Options, Simple},
37};
38
39mod binary;
40mod client_info;
41mod connecting_stream;
42/// Error types.
43pub mod errors;
44mod io;
45/// Pool types.
46pub mod pool;
47mod retry_guard;
48/// ClickHouse types.
49pub mod types;
50
51/// This macro is a convenient way to pass row into a block.
52///
53/// ```rust
54/// # use clickhouse_native_rs::{Block, row, errors::Error};
55/// # fn make_block() -> Result<(), Error> {
56///       let mut block = Block::new();
57///       block.push(row!{customer_id: 1, amount: 2, account_name: "foo"})?;
58///       block.push(row!{customer_id: 4, amount: 4, account_name: "bar"})?;
59///       block.push(row!{customer_id: 5, amount: 5, account_name: "baz"})?;
60/// #     assert_eq!(block.row_count(), 3);
61/// #     Ok(())
62/// # }
63/// # make_block().unwrap()
64/// ```
65///
66/// If a column name has special characters, you can use the alternative syntax
67/// with `=>` to pass an expression as column name:
68///
69/// ```rust
70/// # use clickhouse_native_rs::{Block, row, errors::Error};
71/// # fn make_block() -> Result<(), Error> {
72///       let mut block = Block::new();
73///       block.push(row!{"customer.id" => 1, amount: 2, "account.name" => "foo"})?;
74///       block.push(row!{"customer.id" => 4, amount: 4, "account.name" => "bar"})?;
75///       block.push(row!{"customer.id" => 5, amount: 5, "account.name" => "baz"})?;
76/// #     assert_eq!(block.row_count(), 3);
77/// #     Ok(())
78/// # }
79/// # make_block().unwrap()
80/// ```
81///
82/// You can also use `Vec<(String, Value)>` to construct a row and insert it into a block:
83///
84/// ```rust
85/// # use clickhouse_native_rs::{Block, errors::Error, types::Value};
86/// # fn make_block() -> Result<(), Error> {
87///       let mut block = Block::new();
88///       for i in 1..10 {
89///           let mut row = Vec::new();
90///           for j in 1..10 {
91///               row.push((format!("#{}", j), Value::from(i * j)));
92///           }
93///           block.push(row)?;
94///       }
95///       assert_eq!(block.row_count(), 9);
96/// #     println!("{:?}", block);
97/// #     Ok(())
98/// # }
99/// # make_block().unwrap()
100/// ```
101#[macro_export]
102macro_rules! row {
103    () => { $crate::types::RNil };
104    ( $i:ident, $($tail:tt)* ) => {
105        row!( $($tail)* ).put(stringify!($i).into(), $i.into())
106    };
107    ( $i:ident ) => { row!($i: $i) };
108
109    ( $k:ident: $v:expr ) => {
110        $crate::types::RNil.put(stringify!($k).into(), $v.into())
111    };
112
113    ( $k:ident: $v:expr, $($tail:tt)* ) => {
114        row!( $($tail)* ).put(stringify!($k).into(), $v.into())
115    };
116
117    ( $k:expr => $v:expr ) => {
118        $crate::types::RNil.put($k.into(), $v.into())
119    };
120
121    ( $k:expr => $v:expr, $($tail:tt)* ) => {
122        row!( $($tail)* ).put($k.into(), $v.into())
123    };
124}
125
126#[macro_export]
127macro_rules! try_opt {
128    ($expr:expr) => {
129        match $expr {
130            Ok(val) => val,
131            Err(err) => return Err(err),
132        }
133    };
134}
135
136#[doc(hidden)]
137pub struct Client {
138    _private: (),
139}
140
141/// Clickhouse client handle.
142pub struct ClientHandle {
143    inner: Option<ClickhouseTransport>,
144    context: Context,
145    pool: PoolBinding,
146}
147
148impl fmt::Debug for ClientHandle {
149    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150        f.debug_struct("ClientHandle")
151            .field("server_info", &self.context.server_info)
152            .finish()
153    }
154}
155
156impl Client {
157    #[deprecated(since = "0.1.4", note = "please use Pool to connect")]
158    pub async fn connect(options: Options) -> Result<ClientHandle> {
159        let source = options.into_options_src();
160        Self::open(source, None).await
161    }
162
163    pub(crate) async fn open(source: OptionsSource, pool: Option<Pool>) -> Result<ClientHandle> {
164        let options = try_opt!(source.get());
165        let compress = options.compression.is_enabled();
166        let timeout = options.connection_timeout;
167
168        let context = Context {
169            options: source.clone(),
170            ..Context::default()
171        };
172
173        with_timeout(
174            async move {
175                let addr = match &pool {
176                    None => &options.addr,
177                    Some(p) => p.get_addr(),
178                };
179
180                info!("try to connect to {}", addr);
181                if addr.port() == Some(8123) {
182                    warn!("Port 8123 is the HTTP interface; this client speaks the native TCP protocol (port 9000 by default).");
183                }
184                let mut stream = ConnectingStream::new(addr, &options).await?;
185                stream.set_nodelay(options.nodelay)?;
186                stream.set_keepalive(options.keepalive)?;
187
188                let transport = ClickhouseTransport::new(stream, compress, pool.clone());
189                let mut handle = ClientHandle {
190                    inner: Some(transport),
191                    context,
192                    pool: match pool {
193                        None => PoolBinding::None,
194                        Some(p) => PoolBinding::Detached(p),
195                    },
196                };
197
198                handle.hello().await?;
199                Ok(handle)
200            },
201            timeout,
202        )
203        .await
204    }
205}
206
207impl ClientHandle {
208    pub(crate) async fn hello(&mut self) -> Result<()> {
209        let context = self.context.clone();
210        info!("[hello] -> {:?}", context);
211
212        let mut h = None;
213        let mut info = None;
214        let mut stream = self.get_inner()?.call(Cmd::Hello(context.clone()));
215
216        while let Some(packet) = stream.next().await {
217            match packet {
218                // A Hello read from a connection the server has already
219                // closed is no connection to work with.
220                Ok(Packet::Hello(inner, _)) if inner.is_closed() => {
221                    return Err(Error::Connection(ConnectionError::Broken))
222                }
223                Ok(Packet::Hello(inner, server_info)) => {
224                    info!("[hello] <- {:?}", server_info);
225                    h = Some(inner);
226                    info = Some(server_info);
227                }
228                Ok(Packet::Exception(e)) => return Err(Error::Server(e)),
229                Err(e) => return Err(Error::Io(e)),
230                _ => return Err(Error::Driver(DriverError::UnexpectedPacket)),
231            }
232        }
233
234        // A server that closes the connection without a Hello packet (for
235        // example while it is still starting) leaves nothing to work with.
236        match (h, info) {
237            (Some(inner), Some(server_info)) => {
238                // A server that knows the addendum waits for it before anything else.
239                let revision = client_info::negotiated(server_info.revision);
240                // This client frames packets the old way only.
241                if server_info.chunked_send == "chunked" || server_info.chunked_recv == "chunked" {
242                    return Err(Error::Other(
243                        "the server requires chunked packets (proto_caps), which this client \
244                         does not speak"
245                            .into(),
246                    ));
247                }
248                let inner = if revision >= protocol::DBMS_MIN_PROTOCOL_VERSION_WITH_ADDENDUM {
249                    inner.send_only(Cmd::Addendum(revision)).await?
250                } else {
251                    inner
252                };
253                self.inner = Some(inner);
254                self.context.server_info = server_info;
255                Ok(())
256            }
257            _ => Err(Error::Connection(ConnectionError::Broken)),
258        }
259    }
260
261    pub async fn ping(&mut self) -> Result<()> {
262        let timeout = try_opt!(self.context.options.get()).ping_timeout;
263
264        with_timeout(
265            async move {
266                //info!("[ping]");
267
268                let mut h = None;
269
270                let transport = self.get_inner()?.clear().await?;
271                let mut stream = transport.call(Cmd::Ping);
272
273                while let Some(packet) = stream.next().await {
274                    match packet {
275                        Ok(Packet::Pong(inner)) => {
276                            //info!("[pong]");
277                            h = Some(inner);
278                        }
279                        Ok(Packet::Exception(e)) => return Err(Error::Server(e)),
280                        Err(e) => return Err(Error::Io(e)),
281                        _ => return Err(Error::Driver(DriverError::UnexpectedPacket)),
282                    }
283                }
284
285                // A Pong that arrived with the server closing the connection
286                // does not prove it alive: report it, so the caller reconnects.
287                match h {
288                    Some(h) if !h.is_closed() => {
289                        self.inner = Some(h);
290                        Ok(())
291                    }
292                    _ => Err(Error::Connection(ConnectionError::Broken)),
293                }
294            },
295            timeout,
296        )
297        .await
298    }
299
300    /// Executes Clickhouse `query` on Conn.
301    pub fn query<Q>(&mut self, sql: Q) -> QueryResult<'_>
302    where
303        Query: From<Q>,
304    {
305        let query = Query::from(sql);
306        QueryResult {
307            client: self,
308            query,
309        }
310    }
311
312    /// Convenience method to prepare and execute a single SQL statement.
313    pub async fn execute<Q>(&mut self, sql: Q) -> Result<()>
314    where
315        Query: From<Q>,
316    {
317        let transport = self.execute_(sql).await?;
318        self.keep_transport(transport);
319        Ok(())
320    }
321
322    async fn execute_<Q>(&mut self, sql: Q) -> Result<ClickhouseTransport>
323    where
324        Query: From<Q>,
325    {
326        let timeout = try_opt!(self.context.options.get())
327            .execute_timeout
328            .unwrap_or_else(|| Duration::from_secs(0));
329        let context = self.context.clone();
330        let query = Query::from(sql);
331        with_timeout(
332            async {
333                self.wrap_future(move |c| {
334                    info!("[execute query] {}", query.get_sql());
335
336                    let transport = c.get_inner();
337
338                    async move {
339                        let transport = transport?;
340                        let mut h = None;
341
342                        let transport = transport.clear().await?;
343                        let mut stream = transport.call(Cmd::SendQuery(query, context.clone()));
344
345                        while let Some(packet) = stream.next().await {
346                            match packet {
347                                Ok(Packet::Eof(inner)) => h = Some(inner),
348                                Ok(Packet::Block(_))
349                                | Ok(Packet::ProfileInfo(_))
350                                | Ok(Packet::Progress(_)) => (),
351                                Ok(Packet::Exception(e)) => return Err(Error::Server(e)),
352                                Err(e) => return Err(Error::Io(e)),
353                                _ => return Err(Error::Driver(DriverError::UnexpectedPacket)),
354                            }
355                        }
356
357                        // No end of stream: the server closed the connection.
358                        h.ok_or(Error::Connection(ConnectionError::Broken))
359                    }
360                })
361                .await
362            },
363            timeout,
364        )
365        .await
366    }
367
368    /// Convenience method to insert block of data.
369    pub async fn insert<Q, B>(&mut self, table: Q, block: B) -> Result<()>
370    where
371        Query: From<Q>,
372        B: AsRef<Block>,
373    {
374        let query = Self::make_query(table, block.as_ref())?;
375        let transport = self.insert_(query.clone(), block.as_ref()).await?;
376        self.keep_transport(transport);
377        Ok(())
378    }
379
380    async fn insert_(&mut self, query: Query, block: &Block) -> Result<ClickhouseTransport> {
381        let timeout = try_opt!(self.context.options.get())
382            .insert_timeout
383            .unwrap_or_else(|| Duration::from_secs(0));
384
385        let context = self.context.clone();
386
387        with_timeout(
388            async {
389                self.wrap_future(move |c| {
390                    //info!("[insert]     {}", query.get_sql());
391                    let transport = c.get_inner();
392
393                    async move {
394                        let transport = transport?.clear().await?;
395                        let (transport, dst_block) =
396                            Self::send_insert_query_(transport, context.clone(), query.clone())
397                                .await?;
398                        let casted_block = block.cast_to(&dst_block)?;
399                        let mut chunks = casted_block.chunks(INSERT_BLOCK_SIZE);
400                        let transport =
401                            Self::insert_block_(transport, context.clone(), chunks.next().unwrap())
402                                .await?;
403                        Self::insert_tail_(transport, context, query, chunks).await
404                    }
405                })
406                .await
407            },
408            timeout,
409        )
410        .await
411    }
412
413    async fn insert_tail_(
414        mut transport: ClickhouseTransport,
415        context: Context,
416        query: Query,
417        chunks: ChunkIterator<Simple>,
418    ) -> Result<ClickhouseTransport> {
419        for chunk in chunks {
420            let (transport_, _) =
421                Self::send_insert_query_(transport, context.clone(), query.clone()).await?;
422            transport = Self::insert_block_(transport_, context.clone(), chunk).await?;
423        }
424        Ok(transport)
425    }
426
427    async fn send_insert_query_(
428        transport: ClickhouseTransport,
429        context: Context,
430        query: Query,
431    ) -> Result<(ClickhouseTransport, Block)> {
432        ensure_open(&transport)?;
433        let stream = transport.call(Cmd::SendQuery(query, context));
434        let (transport, b) = stream.read_block().await?;
435        // The server answers an INSERT with a block that describes the table.
436        let dst_block = match b {
437            Some(block) => block,
438            None if transport.is_closed() => {
439                return Err(Error::Connection(ConnectionError::Broken))
440            }
441            None => return Err(Error::Driver(DriverError::UnexpectedPacket)),
442        };
443        Ok((transport, dst_block))
444    }
445
446    async fn insert_block_(
447        transport: ClickhouseTransport,
448        context: Context,
449        block: Block,
450    ) -> Result<ClickhouseTransport> {
451        ensure_open(&transport)?;
452        let send_cmd = Cmd::Union(
453            Box::new(Cmd::SendData(block, context.clone())),
454            Box::new(Cmd::SendData(Block::default(), context)),
455        );
456        let (transport, _) = transport.call(send_cmd).read_block().await?;
457        Ok(transport)
458    }
459
460    fn make_query<Q>(table: Q, block: &Block) -> Result<Query>
461    where
462        Query: From<Q>,
463    {
464        let mut names: Vec<_> = Vec::with_capacity(block.as_ref().column_count());
465        for column in block.as_ref().columns() {
466            names.push(try_opt!(column_name_to_string(column.name())));
467        }
468        let fields = names.join(", ");
469        Ok(Query::from(table).map_sql(|table| format!("INSERT INTO {table} ({fields}) VALUES")))
470    }
471
472    pub(crate) async fn wrap_future<T, R, F>(&mut self, f: F) -> Result<T>
473    where
474        F: FnOnce(&mut Self) -> R + Send,
475        R: Future<Output = Result<T>>,
476        T: 'static,
477    {
478        let ping_before_query = try_opt!(self.context.options.get()).ping_before_query;
479
480        // Without a connection (the last one ended with an error) the check
481        // opens a new one, also when no ping is wanted.
482        if ping_before_query || self.inner.is_none() {
483            self.check_connection().await?;
484        }
485        f(self).await
486    }
487
488    pub(crate) fn wrap_stream<'a, F>(&'a mut self, f: F) -> BoxStream<'a, Result<Block>>
489    where
490        F: (FnOnce(&'a mut Self) -> Result<BlockStream<'a>>) + Send + 'static,
491    {
492        let ping_before_query = match self.context.options.get() {
493            Ok(val) => val.ping_before_query,
494            Err(err) => return Box::pin(stream::once(future::err(err))),
495        };
496
497        if ping_before_query || self.inner.is_none() {
498            let fut: BoxFuture<'a, BoxStream<'a, Result<Block>>> = Box::pin(async move {
499                let inner: BoxStream<'a, Result<Block>> = match self.check_connection().await {
500                    Ok(_) => match f(self) {
501                        Ok(s) => Box::pin(s),
502                        Err(err) => Box::pin(stream::once(future::err(err))),
503                    },
504                    Err(err) => Box::pin(stream::once(future::err(err))),
505                };
506                inner
507            });
508
509            Box::pin(fut.flatten_stream())
510        } else {
511            match f(self) {
512                Ok(s) => Box::pin(s),
513                Err(err) => Box::pin(stream::once(future::err(err))),
514            }
515        }
516    }
517
518    /// Check connection and try to reconnect if necessary.
519    pub async fn check_connection(&mut self) -> Result<()> {
520        self.pool.detach();
521
522        let source = self.context.options.clone();
523        let pool = self.pool.clone();
524
525        let (send_retries, retry_timeout) = {
526            let options = try_opt!(source.get());
527            (options.send_retries, options.retry_timeout)
528        };
529
530        retry_guard(self, &source, pool.into(), send_retries, retry_timeout).await?;
531
532        if !self.pool.is_attached() && self.pool.is_some() {
533            self.pool.attach();
534        }
535
536        Ok(())
537    }
538
539    /// Keeps the transport for the next command, unless the server has already
540    /// closed the connection: the command it carried is complete, but the
541    /// next one would fail, so let `check_connection` open a new one instead.
542    pub(crate) fn keep_transport(&mut self, transport: ClickhouseTransport) {
543        if !transport.is_closed() {
544            self.inner = Some(transport);
545        }
546    }
547
548    pub(crate) fn set_inside(&self, value: bool) {
549        if let Some(ref inner) = self.inner {
550            inner.set_inside(value);
551        } else {
552            unreachable!()
553        }
554    }
555
556    fn get_inner(&mut self) -> Result<ClickhouseTransport> {
557        self.inner
558            .take()
559            .ok_or(Error::Connection(ConnectionError::Broken))
560    }
561}
562
563/// Refuses to send a command on a connection the server has already closed.
564fn ensure_open(transport: &ClickhouseTransport) -> Result<()> {
565    if transport.is_closed() {
566        return Err(Error::Connection(ConnectionError::Broken));
567    }
568    Ok(())
569}
570
571fn column_name_to_string(name: &str) -> Result<String> {
572    if name.chars().all(|ch| ch.is_numeric()) {
573        return Ok(name.to_string());
574    }
575
576    if name.chars().any(|ch| ch == '`') {
577        let err = format!("Column name {name:?} shouldn't contains backticks.");
578        return Err(Error::Other(err.into()));
579    }
580
581    Ok(format!("`{name}`"))
582}
583
584#[cfg(feature = "async_std")]
585async fn with_timeout<F, T>(future: F, duration: Duration) -> F::Output
586where
587    F: Future<Output = Result<T>>,
588{
589    use async_std::io;
590    use futures_util::future::TryFutureExt;
591
592    io::timeout(duration, future.map_err(Into::into))
593        .map_err(Into::into)
594        .await
595}
596
597#[cfg(not(feature = "async_std"))]
598async fn with_timeout<F, T>(future: F, timeout: Duration) -> F::Output
599where
600    F: Future<Output = Result<T>>,
601{
602    tokio::time::timeout(timeout, future).await?
603}
604
605#[cfg(test)]
606pub(crate) mod test_misc {
607    use crate::*;
608    use std::env;
609
610    use lazy_static::lazy_static;
611
612    lazy_static! {
613        pub static ref DATABASE_URL: String = env::var("DATABASE_URL").unwrap_or_else(|_| {
614            "tcp://localhost:9000?compression=lz4&ping_timeout=1s&retry_timeout=2s".into()
615        });
616    }
617
618    #[test]
619    fn test_column_name_to_string() {
620        assert_eq!(column_name_to_string("id").unwrap(), "`id`");
621        assert_eq!(column_name_to_string("234").unwrap(), "234");
622        assert_eq!(column_name_to_string("ns:attr").unwrap(), "`ns:attr`");
623        assert!(column_name_to_string("`").is_err());
624    }
625}