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