Skip to main content

clickhouse_native_rs/types/
query.rs

1use std::fmt;
2
3use crate::types::Value;
4
5/// A query: its text, an id, and the values of its `{name:Type}`
6/// parameters.
7#[derive(Clone)]
8pub struct Query {
9    sql: String,
10    id: String,
11    params: Vec<(String, Value)>,
12}
13
14impl Query {
15    pub fn new(sql: impl AsRef<str>) -> Self {
16        Self {
17            sql: sql.as_ref().to_string(),
18            id: "".to_string(),
19            params: Vec::new(),
20        }
21    }
22
23    pub fn id(self, id: impl AsRef<str>) -> Self {
24        Self {
25            id: id.as_ref().to_string(),
26            ..self
27        }
28    }
29
30    /// Binds `value` to the `{name:Type}` placeholders of the query, which
31    /// the server fills in: the value is sent as the text the server parses
32    /// for `Type`, never spliced into the SQL. Binding a name again replaces
33    /// its value. A parameter of a `Nullable` type that is not bound is NULL.
34    ///
35    /// ```rust,no_run
36    /// # use clickhouse_native_rs::{types::Query, Pool};
37    /// # async fn run(pool: Pool) -> Result<(), clickhouse_native_rs::errors::Error> {
38    /// let mut client = pool.get_handle().await?;
39    /// let query = Query::new("SELECT name FROM users WHERE id = {id:UInt32} AND city = {city:String}")
40    ///     .param("id", 42_u32)
41    ///     .param("city", "O'Fallon");
42    /// let block = client.query(query).fetch_all().await?;
43    /// # Ok(()) }
44    /// ```
45    pub fn param(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
46        let name = name.into();
47        let value = value.into();
48        match self.params.iter_mut().find(|(bound, _)| *bound == name) {
49            Some((_, bound)) => *bound = value,
50            None => self.params.push((name, value)),
51        }
52        self
53    }
54
55    pub(crate) fn get_sql(&self) -> &str {
56        &self.sql
57    }
58
59    pub(crate) fn get_id(&self) -> &str {
60        &self.id
61    }
62
63    pub(crate) fn get_params(&self) -> &[(String, Value)] {
64        &self.params
65    }
66
67    pub(crate) fn map_sql<F>(self, f: F) -> Self
68    where
69        F: Fn(&str) -> String,
70    {
71        Self {
72            sql: f(&self.sql),
73            ..self
74        }
75    }
76}
77
78/// The names of the parameters, not their values, which may be secrets.
79impl fmt::Debug for Query {
80    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81        let names: Vec<&str> = self.params.iter().map(|(name, _)| name.as_str()).collect();
82        f.debug_struct("Query")
83            .field("sql", &self.sql)
84            .field("id", &self.id)
85            .field("params", &names)
86            .finish()
87    }
88}
89
90impl<T> From<T> for Query
91where
92    T: AsRef<str>,
93{
94    fn from(source: T) -> Self {
95        Self::new(source)
96    }
97}