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