Skip to main content

encore/storage/clickhouse/
param.rs

1//! Query parameters: the values of a query's `{name:Type}` placeholders.
2
3use std::collections::{BTreeMap, HashMap};
4use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
5
6use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};
7use uuid::Uuid;
8
9use super::Value;
10
11/// A query parameter value accepted by [`Query::param`](super::Query::param)
12/// and [`Exec::param`](super::Exec::param).
13///
14/// Because ClickHouse parses parameters according to the type declared in the
15/// SQL (`{id:UInt64}`), any compatible Rust representation works: an `i64` in
16/// range works for `UInt8`, and a string works for `Decimal`, `IPv4`, or
17/// `DateTime`.
18///
19/// | Rust | Sent as |
20/// |---|---|
21/// | integers, floats, `bool` | the number, `true`/`false` |
22/// | `&str`, `String` | the text |
23/// | `Vec<u8>`, `&[u8]` | the bytes, as a `String` |
24/// | [`uuid::Uuid`] | the hyphenated form |
25/// | [`chrono::DateTime<Utc>`], [`chrono::NaiveDateTime`] (as UTC) | Unix seconds with a fraction, so no time zone applies |
26/// | [`chrono::NaiveDate`] | `YYYY-MM-DD` |
27/// | [`std::net::IpAddr`] and its variants | dotted / RFC 5952 text |
28/// | `Option<T>` | `T`, or `NULL` for `None` (declare the type `Nullable(…)`) |
29/// | `Vec<T>` (`T` not `u8`) | an array |
30/// | `HashMap<K, V>`, `BTreeMap<K, V>` | a map |
31/// | [`Value`] | the value as it is: the explicit form, for any type |
32///
33/// Use [`Value`] directly for ClickHouse types without a dedicated Rust type
34/// here, such as exact decimals (`Value::Decimal("12.30".into())`) or tuples
35/// (`Value::Tuple(vec![1i64.into(), "a".into()])`).
36#[derive(Clone, Debug, PartialEq)]
37pub struct Param(pub(super) Value);
38
39impl Param {
40    /// `NULL`, for a `Nullable(…)` parameter.
41    pub fn null() -> Self {
42        Param(Value::Null)
43    }
44
45    /// The value the parameter is sent as.
46    pub fn value(&self) -> &Value {
47        &self.0
48    }
49}
50
51impl From<Value> for Param {
52    fn from(v: Value) -> Self {
53        Param(v)
54    }
55}
56
57/// Types that can be elements of a `Vec<T>` array parameter.
58///
59/// Every parameter type except `u8` implements this trait, because `Vec<u8>` is
60/// sent as raw bytes. For an array of `UInt8`, pass `Vec<u16>` or
61/// [`Value::Array`].
62pub trait ArrayElement: Into<Param> {}
63
64macro_rules! scalar {
65    ($($ty:ty => |$v:ident| $make:expr),* $(,)?) => {
66        $(
67            impl From<$ty> for Param {
68                fn from($v: $ty) -> Self {
69                    Param($make)
70                }
71            }
72        )*
73    };
74}
75
76scalar! {
77    u8 => |v| Value::UInt(v.into()),
78    u16 => |v| Value::UInt(v.into()),
79    u32 => |v| Value::UInt(v.into()),
80    u64 => |v| Value::UInt(v),
81    usize => |v| Value::UInt(v as u64),
82    i8 => |v| Value::Int(v.into()),
83    i16 => |v| Value::Int(v.into()),
84    i32 => |v| Value::Int(v.into()),
85    i64 => |v| Value::Int(v),
86    isize => |v| Value::Int(v as i64),
87    i128 => |v| Value::Int128(v),
88    u128 => |v| Value::UInt128(v),
89    f32 => |v| Value::Float32(v),
90    f64 => |v| Value::Float64(v),
91    bool => |v| Value::Bool(v),
92    &str => |v| Value::from(v),
93    String => |v| Value::from(v),
94    &String => |v| Value::from(v.as_str()),
95    Vec<u8> => |v| Value::String(v),
96    &[u8] => |v| Value::String(v.to_vec()),
97    Uuid => |v| Value::Uuid(v),
98    DateTime<Utc> => |v| Value::from(v),
99    NaiveDateTime => |v| Value::from(v.and_utc()),
100    NaiveDate => |v| Value::date(v),
101    Ipv4Addr => |v| Value::Ipv4(v),
102    Ipv6Addr => |v| Value::Ipv6(v),
103    IpAddr => |v| match v {
104        IpAddr::V4(ip) => Value::Ipv4(ip),
105        IpAddr::V6(ip) => Value::Ipv6(ip),
106    },
107}
108
109macro_rules! element {
110    ($($ty:ty),* $(,)?) => {
111        $(impl ArrayElement for $ty {})*
112    };
113}
114
115element!(
116    u16,
117    u32,
118    u64,
119    usize,
120    i8,
121    i16,
122    i32,
123    i64,
124    isize,
125    i128,
126    u128,
127    f32,
128    f64,
129    bool,
130    &str,
131    String,
132    &String,
133    Vec<u8>,
134    &[u8],
135    Uuid,
136    DateTime<Utc>,
137    NaiveDateTime,
138    NaiveDate,
139    Ipv4Addr,
140    Ipv6Addr,
141    IpAddr,
142    Value,
143    Param,
144);
145
146impl<T: Into<Param>> ArrayElement for Option<T> {}
147impl<T: ArrayElement> ArrayElement for Vec<T> {}
148impl<K: Into<Param>, V: Into<Param>, S> ArrayElement for HashMap<K, V, S> {}
149impl<K: Into<Param>, V: Into<Param>> ArrayElement for BTreeMap<K, V> {}
150
151impl<T: Into<Param>> From<Option<T>> for Param {
152    fn from(v: Option<T>) -> Self {
153        v.map_or(Param(Value::Null), Into::into)
154    }
155}
156
157impl<T: ArrayElement> From<Vec<T>> for Param {
158    fn from(v: Vec<T>) -> Self {
159        Param(Value::Array(v.into_iter().map(|e| e.into().0).collect()))
160    }
161}
162
163impl<K: Into<Param>, V: Into<Param>, S> From<HashMap<K, V, S>> for Param {
164    fn from(m: HashMap<K, V, S>) -> Self {
165        Param(Value::Map(
166            m.into_iter()
167                .map(|(k, v)| (k.into().0, v.into().0))
168                .collect(),
169        ))
170    }
171}
172
173impl<K: Into<Param>, V: Into<Param>> From<BTreeMap<K, V>> for Param {
174    fn from(m: BTreeMap<K, V>) -> Self {
175        Param(Value::Map(
176            m.into_iter()
177                .map(|(k, v)| (k.into().0, v.into().0))
178                .collect(),
179        ))
180    }
181}