1#![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;
42pub mod errors;
44mod io;
45pub mod pool;
47mod retry_guard;
48pub mod types;
50
51#[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
141pub 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 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 match (h, info) {
237 (Some(inner), Some(server_info)) => {
238 let revision = client_info::negotiated(server_info.revision);
240 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 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 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 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 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 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 h.ok_or(Error::Connection(ConnectionError::Broken))
359 }
360 })
361 .await
362 },
363 timeout,
364 )
365 .await
366 }
367
368 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 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 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 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 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 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
563fn 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}