1use std::pin::Pin;
4use std::sync::Arc;
5use std::time::Duration;
6
7use bytes::{Buf, Bytes, BytesMut};
8use futures_util::{Stream, StreamExt};
9use tokio::sync::{OwnedSemaphorePermit, Semaphore};
10use url::Url;
11
12use crate::error::exception_in;
13use crate::rowbinary::{Reader, Short};
14use crate::types::Type;
15use crate::value::Value;
16use crate::Error;
17
18pub const DEFAULT_MAX_CONNECTIONS: usize = 100;
20
21const RESPONSE_BUFFER: &str = "1048576";
26
27#[derive(Clone, Default)]
29pub struct Credentials {
30 pub user: String,
31 pub password: String,
32}
33
34impl std::fmt::Debug for Credentials {
35 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36 f.debug_struct("Credentials")
37 .field("user", &self.user)
38 .finish_non_exhaustive()
39 }
40}
41
42#[derive(Clone, Default, Debug)]
44pub struct TlsConfig {
45 pub ca_cert_pem: Option<String>,
47 pub skip_hostname_verification: bool,
48 pub skip_ca_validation: bool,
49 pub client_cert: Option<(String, String)>,
51}
52
53#[derive(Clone, Debug)]
54pub struct ClientConfig {
55 pub url: String,
58 pub tls: TlsConfig,
59 pub max_connections: usize,
61 pub credentials: Option<Credentials>,
63}
64
65#[derive(Clone)]
67pub struct Client {
68 inner: Arc<Inner>,
69}
70
71struct Inner {
72 http: reqwest::Client,
73 base: Url,
74 credentials: Option<Credentials>,
75 limit: Arc<Semaphore>,
76}
77
78impl std::fmt::Debug for Client {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 f.debug_struct("Client")
81 .field("url", &self.inner.base.as_str())
82 .finish_non_exhaustive()
83 }
84}
85
86#[derive(Clone, Debug, Default)]
88pub struct Request {
89 pub sql: String,
90 pub database: Option<String>,
93 pub params: Vec<(String, Vec<u8>)>,
95 pub settings: Vec<(String, String)>,
96 pub query_id: Option<String>,
97 pub credentials: Option<Credentials>,
99}
100
101impl Request {
102 pub fn new(sql: impl Into<String>) -> Self {
103 Request {
104 sql: sql.into(),
105 ..Default::default()
106 }
107 }
108
109 pub fn database(mut self, db: impl Into<String>) -> Self {
110 self.database = Some(db.into());
111 self
112 }
113
114 pub fn param(mut self, name: impl Into<String>, value: &Value) -> Self {
116 self.params.push((name.into(), value.to_param_text()));
117 self
118 }
119
120 pub fn setting(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
121 self.settings.push((name.into(), value.into()));
122 self
123 }
124
125 pub fn query_id(mut self, id: impl Into<String>) -> Self {
126 self.query_id = Some(id.into());
127 self
128 }
129
130 pub fn credentials(mut self, c: Credentials) -> Self {
131 self.credentials = Some(c);
132 self
133 }
134}
135
136#[derive(Clone, Debug, Default, PartialEq, Eq)]
138pub struct Summary {
139 pub query_id: String,
140 pub read_rows: u64,
141 pub read_bytes: u64,
142 pub written_rows: u64,
143 pub written_bytes: u64,
144 pub result_rows: u64,
145 pub elapsed_ns: u64,
146}
147
148impl Summary {
149 fn from_headers(h: &reqwest::header::HeaderMap) -> Summary {
150 let mut s = Summary {
151 query_id: header(h, "x-clickhouse-query-id").unwrap_or_default(),
152 ..Default::default()
153 };
154 let Some(json) = header(h, "x-clickhouse-summary") else {
155 return s;
156 };
157 let Ok(serde_json::Value::Object(m)) = serde_json::from_str::<serde_json::Value>(&json)
158 else {
159 return s;
160 };
161 let num = |k: &str| -> u64 {
162 match m.get(k) {
163 Some(serde_json::Value::String(v)) => v.parse().unwrap_or(0),
164 Some(serde_json::Value::Number(n)) => n.as_u64().unwrap_or(0),
165 _ => 0,
166 }
167 };
168 s.read_rows = num("read_rows");
169 s.read_bytes = num("read_bytes");
170 s.written_rows = num("written_rows");
171 s.written_bytes = num("written_bytes");
172 s.result_rows = num("result_rows");
173 s.elapsed_ns = num("elapsed_ns");
174 s
175 }
176}
177
178fn header(h: &reqwest::header::HeaderMap, name: &str) -> Option<String> {
179 h.get(name)?.to_str().ok().map(str::to_string)
180}
181
182#[derive(Clone, Debug, PartialEq)]
184pub struct Column {
185 pub name: String,
186 pub type_name: String,
188 pub ty: Type,
189}
190
191impl Client {
192 pub fn new(cfg: ClientConfig) -> Result<Client, Error> {
193 let base = Url::parse(&cfg.url)
194 .map_err(|e| Error::InvalidArgument(format!("ClickHouse URL {:?}: {e}", cfg.url)))?;
195 if !matches!(base.scheme(), "http" | "https") {
196 return Err(Error::InvalidArgument(format!(
197 "ClickHouse URL {:?}: the scheme must be http or https",
198 cfg.url
199 )));
200 }
201 let mut b = reqwest::Client::builder()
202 .connect_timeout(Duration::from_secs(10))
203 .pool_idle_timeout(Duration::from_secs(2))
206 .tcp_nodelay(true);
207 if let Some(ca) = &cfg.tls.ca_cert_pem {
208 let cert = reqwest::Certificate::from_pem(ca.as_bytes())
209 .map_err(|e| Error::InvalidArgument(format!("the server CA certificate: {e}")))?;
210 b = b.add_root_certificate(cert);
211 }
212 if cfg.tls.skip_ca_validation {
213 b = b.danger_accept_invalid_certs(true);
214 }
215 if cfg.tls.skip_hostname_verification {
216 b = b.danger_accept_invalid_hostnames(true);
217 }
218 if let Some((cert, key)) = &cfg.tls.client_cert {
219 let pem = format!("{cert}\n{key}");
220 let id = reqwest::Identity::from_pem(pem.as_bytes())
221 .map_err(|e| Error::InvalidArgument(format!("the client certificate: {e}")))?;
222 b = b.identity(id);
223 }
224 let http = b
225 .build()
226 .map_err(|e| Error::InvalidArgument(format!("build the HTTP client: {e}")))?;
227 let max = if cfg.max_connections == 0 {
228 DEFAULT_MAX_CONNECTIONS
229 } else {
230 cfg.max_connections
231 };
232 Ok(Client {
233 inner: Arc::new(Inner {
234 http,
235 base,
236 credentials: cfg.credentials,
237 limit: Arc::new(Semaphore::new(max)),
238 }),
239 })
240 }
241
242 pub fn url(&self) -> &Url {
244 &self.inner.base
245 }
246
247 pub async fn ping(&self) -> Result<(), Error> {
249 let url = self
250 .inner
251 .base
252 .join("ping")
253 .map_err(|e| Error::InvalidArgument(e.to_string()))?;
254 let resp = self.inner.http.get(url).send().await.map_err(transport)?;
255 if resp.status().is_success() {
256 Ok(())
257 } else {
258 Err(Error::Unavailable(format!("ping: {}", resp.status())))
259 }
260 }
261
262 pub async fn query(&self, req: Request) -> Result<Rows, Error> {
264 let mut req = req;
265 default_setting(&mut req, "default_format", "RowBinaryWithNamesAndTypes");
266 default_setting(&mut req, "output_format_binary_write_json_as_string", "1");
267 default_setting(&mut req, "http_response_buffer_size", RESPONSE_BUFFER);
268 let body = req.sql.clone().into_bytes();
269 let (resp, permit) = self.send(&req, None, body).await?;
270 let summary = Summary::from_headers(resp.headers());
271 let marker = header(resp.headers(), "x-clickhouse-exception-tag")
274 .map(|tag| format!("__exception__\r\n{tag}").into_bytes());
275 let mut rows = Rows {
276 columns: Arc::from(Vec::new()),
277 stream: Box::pin(resp.bytes_stream()),
278 buf: BytesMut::new(),
279 done: false,
280 summary,
281 marker,
282 scanned: 0,
283 exception: None,
284 max_row_bytes: None,
285 _permit: permit,
286 };
287 rows.read_header().await?;
288 Ok(rows)
289 }
290
291 pub async fn exec(&self, req: Request) -> Result<Summary, Error> {
293 let body = req.sql.clone().into_bytes();
294 let (resp, _permit) = self.send(&req, None, body).await?;
295 let summary = Summary::from_headers(resp.headers());
296 let body = resp.bytes().await.map_err(transport)?;
299 if let Some(e) = exception_in(tail(&body)) {
300 return Err(e);
301 }
302 Ok(summary)
303 }
304
305 pub async fn insert(
311 &self,
312 req: Request,
313 table: &str,
314 columns: &[String],
315 rows: &[Vec<Option<Value>>],
316 ) -> Result<Summary, Error> {
317 if columns.is_empty() {
318 return Err(Error::InvalidArgument(
319 "an insert needs at least one column".into(),
320 ));
321 }
322 let mut sql = format!("INSERT INTO {} (", quote_table(table)?);
323 for (i, c) in columns.iter().enumerate() {
324 if i > 0 {
325 sql.push_str(", ");
326 }
327 sql.push_str("e_ident(c));
328 }
329 sql.push_str(") FORMAT JSONEachRow");
330
331 let mut body = String::new();
332 for row in rows {
333 if row.len() != columns.len() {
334 return Err(Error::InvalidArgument(format!(
335 "a row has {} values for {} columns",
336 row.len(),
337 columns.len()
338 )));
339 }
340 body.push('{');
341 let mut first = true;
342 for (c, v) in columns.iter().zip(row) {
343 let Some(v) = v else { continue };
344 if !first {
345 body.push(',');
346 }
347 first = false;
348 body.push_str(&serde_json::Value::String(c.clone()).to_string());
349 body.push(':');
350 v.write_json(&mut body);
351 }
352 body.push_str("}\n");
353 }
354 let mut req = req;
355 req.sql = sql;
356 default_setting(&mut req, "date_time_input_format", "best_effort");
357 default_setting(&mut req, "input_format_json_named_tuples_as_objects", "0");
359 default_setting(&mut req, "input_format_defaults_for_omitted_fields", "1");
360 let (resp, _permit) = self.send(&req, Some(()), body.into_bytes()).await?;
361 let summary = Summary::from_headers(resp.headers());
362 let body = resp.bytes().await.map_err(transport)?;
363 if let Some(e) = exception_in(tail(&body)) {
364 return Err(e);
365 }
366 Ok(summary)
367 }
368
369 async fn send(
372 &self,
373 req: &Request,
374 data: Option<()>,
375 body: Vec<u8>,
376 ) -> Result<(reqwest::Response, OwnedSemaphorePermit), Error> {
377 let permit = self
378 .inner
379 .limit
380 .clone()
381 .acquire_owned()
382 .await
383 .map_err(|_| Error::Unavailable("the client is closed".into()))?;
384
385 let mut url = self.inner.base.clone();
386 let mut q = String::new();
387 let mut add = |k: &[u8], v: &[u8]| {
388 if !q.is_empty() {
389 q.push('&');
390 }
391 q.extend(url::form_urlencoded::byte_serialize(k));
392 q.push('=');
393 q.extend(url::form_urlencoded::byte_serialize(v));
394 };
395 if let Some(db) = &req.database {
396 add(b"database", db.as_bytes());
397 }
398 if let Some(id) = &req.query_id {
399 add(b"query_id", id.as_bytes());
400 }
401 if data.is_some() {
402 add(b"query", req.sql.as_bytes());
403 }
404 for (k, v) in &req.settings {
405 add(k.as_bytes(), v.as_bytes());
406 }
407 for (k, v) in &req.params {
408 let key = format!("param_{k}");
409 add(key.as_bytes(), v);
410 }
411 url.set_query(if q.is_empty() { None } else { Some(&q) });
412
413 let mut r = self.inner.http.post(url).body(body);
414 if let Some(c) = req.credentials.as_ref().or(self.inner.credentials.as_ref()) {
415 r = r
416 .header("X-ClickHouse-User", &c.user)
417 .header("X-ClickHouse-Key", &c.password);
418 }
419 let resp = r.send().await.map_err(transport)?;
420 if !resp.status().is_success() {
421 let code =
422 header(resp.headers(), "x-clickhouse-exception-code").and_then(|c| c.parse().ok());
423 let status = resp.status();
424 let text = resp.text().await.unwrap_or_default();
425 if text.trim().is_empty() {
426 return Err(Error::Server {
427 code: code.unwrap_or_default(),
428 name: String::new(),
429 message: format!("ClickHouse answered {status}"),
430 });
431 }
432 return Err(Error::from_exception(&text, code));
433 }
434 Ok((resp, permit))
435 }
436}
437
438fn default_setting(req: &mut Request, name: &str, value: &str) {
440 if !req.settings.iter().any(|(k, _)| k == name) {
441 req.settings.push((name.into(), value.into()));
442 }
443}
444
445fn tail(b: &[u8]) -> &[u8] {
447 &b[b.len().saturating_sub(64 * 1024)..]
448}
449
450fn transport(e: reqwest::Error) -> Error {
451 if e.is_connect() || e.is_timeout() {
452 Error::Unavailable(error_chain(&e))
453 } else if e.is_body() || e.is_decode() {
454 Error::Decode(error_chain(&e))
455 } else {
456 Error::Unavailable(error_chain(&e))
457 }
458}
459
460fn error_chain(e: &dyn std::error::Error) -> String {
461 let mut s = e.to_string();
462 let mut src = e.source();
463 while let Some(c) = src {
464 s.push_str(": ");
465 s.push_str(&c.to_string());
466 src = c.source();
467 }
468 s
469}
470
471pub fn quote_ident(name: &str) -> String {
473 let mut s = String::with_capacity(name.len() + 2);
474 s.push('`');
475 for c in name.chars() {
476 match c {
477 '`' => s.push_str("\\`"),
478 '\\' => s.push_str("\\\\"),
479 c => s.push(c),
480 }
481 }
482 s.push('`');
483 s
484}
485
486pub fn quote_table(table: &str) -> Result<String, Error> {
488 let parts: Vec<&str> = match table.split_once('.') {
489 Some((db, t)) => vec![db, t],
490 None => vec![table],
491 };
492 if parts.iter().any(|p| p.is_empty()) {
493 return Err(Error::InvalidArgument(format!(
494 "invalid table name {table:?}"
495 )));
496 }
497 Ok(parts
498 .into_iter()
499 .map(quote_ident)
500 .collect::<Vec<_>>()
501 .join("."))
502}
503
504pub struct Rows {
508 columns: Arc<[Column]>,
509 stream: Pin<Box<dyn Stream<Item = reqwest::Result<Bytes>> + Send>>,
510 buf: BytesMut,
511 done: bool,
512 summary: Summary,
513 marker: Option<Vec<u8>>,
515 scanned: usize,
517 exception: Option<Error>,
519 max_row_bytes: Option<usize>,
521 _permit: OwnedSemaphorePermit,
522}
523
524impl std::fmt::Debug for Rows {
525 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
526 f.debug_struct("Rows")
527 .field("columns", &self.columns)
528 .finish_non_exhaustive()
529 }
530}
531
532impl Rows {
533 pub fn columns(&self) -> &Arc<[Column]> {
534 &self.columns
535 }
536
537 pub fn summary(&self) -> &Summary {
540 &self.summary
541 }
542
543 pub fn max_row_bytes(&mut self, bytes: usize) {
549 self.max_row_bytes = Some(bytes);
550 }
551
552 async fn fill(&mut self) -> Result<bool, Error> {
553 if self.exception.is_some() {
554 self.done = true;
555 return Ok(false);
556 }
557 match self.stream.next().await {
558 Some(Ok(chunk)) => {
559 self.buf.extend_from_slice(&chunk);
560 self.find_exception();
561 Ok(true)
562 }
563 Some(Err(e)) => {
564 self.done = true;
565 Err(exception_in(&self.buf).unwrap_or_else(|| transport(e)))
566 }
567 None => {
568 self.done = true;
569 Ok(false)
570 }
571 }
572 }
573
574 fn find_exception(&mut self) {
577 let Some(marker) = &self.marker else { return };
578 let from = self.scanned.saturating_sub(marker.len());
579 let found = self.buf[from..]
580 .windows(marker.len())
581 .position(|w| w == marker.as_slice());
582 match found {
583 Some(at) => {
584 let at = from + at;
585 let text = self.buf.split_off(at);
586 if self.buf.ends_with(b"\r\n") {
588 self.buf.truncate(self.buf.len() - 2);
589 }
590 self.exception = Some(exception_in(&text).unwrap_or_else(|| {
591 Error::from_exception(&String::from_utf8_lossy(&text), None)
592 }));
593 self.scanned = self.buf.len();
594 }
595 None => self.scanned = self.buf.len(),
596 }
597 }
598
599 fn consume(&mut self, n: usize) {
601 self.buf.advance(n);
602 self.scanned = self.scanned.saturating_sub(n);
603 }
604
605 fn ended(&mut self, what: &str) -> Error {
607 if let Some(e) = self.exception.take() {
608 return e;
609 }
610 exception_in(&self.buf).unwrap_or_else(|| Error::Decode(what.into()))
611 }
612
613 async fn read_header(&mut self) -> Result<(), Error> {
614 loop {
615 if !self.buf.is_empty() {
616 let mut r = Reader::new(&self.buf);
617 match header_of(&mut r) {
618 Ok(cols) => {
619 let used = r.pos;
620 self.consume(used);
621 self.columns = Arc::from(cols);
622 return Ok(());
623 }
624 Err(Short::Incomplete) => {}
625 Err(Short::Invalid(e)) => return Err(exception_in(&self.buf).unwrap_or(e)),
626 }
627 }
628 if self.done {
629 if self.buf.is_empty() && self.exception.is_none() {
631 return Ok(());
632 }
633 return Err(self.ended("truncated header"));
634 }
635 self.fill().await?;
636 }
637 }
638
639 pub async fn next(&mut self) -> Result<Option<Vec<Value>>, Error> {
641 loop {
642 if !self.buf.is_empty() {
643 let window = match self.max_row_bytes {
646 Some(max) => &self.buf[..self.buf.len().min(max)],
647 None => &self.buf[..],
648 };
649 let mut r = Reader::new(window);
650 let mut row = Vec::with_capacity(self.columns.len());
651 let mut short = None;
652 for c in self.columns.iter() {
653 match r.value(&c.ty) {
654 Ok(v) => row.push(v),
655 Err(e) => {
656 short = Some(e);
657 break;
658 }
659 }
660 }
661 match short {
662 None => {
663 let used = r.pos;
664 self.consume(used);
665 return Ok(Some(row));
666 }
667 Some(Short::Incomplete) => {
668 if let Some(max) = self.max_row_bytes {
670 if self.buf.len() >= max {
671 return Err(Error::InvalidArgument(format!(
672 "a row of the result is larger than {max} bytes"
673 )));
674 }
675 }
676 }
677 Some(Short::Invalid(e)) => {
678 return Err(self.exception.take().unwrap_or(e));
679 }
680 }
681 }
682 if self.done {
683 if self.buf.is_empty() && self.exception.is_none() {
684 return Ok(None);
685 }
686 return Err(self.ended("truncated row"));
687 }
688 self.fill().await?;
689 }
690 }
691
692 pub async fn collect(mut self) -> Result<Vec<Vec<Value>>, Error> {
694 let mut out = Vec::new();
695 while let Some(r) = self.next().await? {
696 out.push(r);
697 }
698 Ok(out)
699 }
700}
701
702fn header_of(r: &mut Reader<'_>) -> Result<Vec<Column>, Short> {
703 let n = r.varint()?;
704 if n > 100_000 {
705 return Err(Short::Invalid(Error::Decode(format!(
706 "implausible column count {n}"
707 ))));
708 }
709 let mut names = Vec::with_capacity(n as usize);
710 for _ in 0..n {
711 names.push(r.string()?);
712 }
713 let mut cols = Vec::with_capacity(n as usize);
714 for name in names {
715 let type_name = r.string()?;
716 let ty = Type::parse(&type_name)?;
717 cols.push(Column {
718 name,
719 type_name,
720 ty,
721 });
722 }
723 Ok(cols)
724}