clickhouse_native_rs/types/
query.rs1use std::fmt;
2
3use crate::types::Value;
4
5#[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 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
78impl 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}