clickhouse_client/query/exec/
mod.rs

1//! Query executor
2
3#[cfg(test)]
4mod tests;
5
6use crate::{
7    error::Error,
8    intf::Interface,
9    value::{ChValue, Value},
10    Client,
11};
12
13use super::{Format, Query, QueryData, QueryResponse, SqlStatement};
14
15/// Query executor
16#[derive(Debug)]
17pub struct QueryExecutor<'a, T>
18where
19    T: Interface,
20{
21    /// Client
22    client: &'a Client<T>,
23    /// Query
24    query: Query,
25}
26
27impl<T> Client<T>
28where
29    T: Interface,
30{
31    /// Prepares a new query
32    pub fn query(&self, query: &str) -> QueryExecutor<T> {
33        QueryExecutor {
34            client: self,
35            query: Query {
36                statement: query.to_string(),
37                db: self.db.clone(),
38                credentials: self.credentials.clone(),
39                ..Default::default()
40            },
41        }
42    }
43}
44
45impl<'a, T> QueryExecutor<'a, T>
46where
47    T: Interface,
48{
49    /// Binds the raw query with query parameters
50    ///
51    /// Query parameters are defined by `??`
52    pub fn bind_val(mut self, value: impl ChValue) -> Self {
53        self.query.statement = self.query.statement.bind_val(value);
54        self
55    }
56
57    /// Binds the query with a raw parameter which is not formatted
58    ///
59    /// For instance, strings are not enclosed by `'`.
60    ///
61    /// Query parameters are defined by `??`
62    pub fn bind_str(mut self, value: &str) -> Self {
63        self.query.statement = self.query.statement.bind_str(value);
64        self
65    }
66
67    /// Binds the raw query with query parameters
68    pub fn bind_val_list(mut self, values: Vec<Value>) -> Self {
69        self.query.statement = self.query.statement.bind_val_list(values);
70        self
71    }
72
73    /// Binds the query with strings
74    pub fn bind_str_list(mut self, values: Vec<&str>) -> Self {
75        self.query.statement = self.query.statement.bind_str_list(values);
76        self
77    }
78
79    /// Asssigns the query data
80    pub fn data(mut self, table: QueryData) -> Self {
81        self.query.data = Some(table);
82        self
83    }
84
85    /// Assigns the target DB
86    pub fn db(mut self, db: Option<&str>) -> Self {
87        self.query.db = db.map(|d| d.to_string());
88        self
89    }
90
91    /// Assigns the format
92    pub fn format(mut self, format: Format) -> Self {
93        self.query.format = Some(format);
94        self
95    }
96
97    /// Executes the query
98    #[tracing::instrument(skip(self))]
99    pub async fn exec(self) -> Result<QueryResponse, Error> {
100        self.client.send(self.query).await
101    }
102}