encore-dev 2.0.0-beta.16

Rust SDK for Encore applications
Documentation
//! Query parameters: the values of a query's `{name:Type}` placeholders.

use std::collections::{BTreeMap, HashMap};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};
use uuid::Uuid;

use super::Value;

/// A query parameter value accepted by [`Query::param`](super::Query::param)
/// and [`Exec::param`](super::Exec::param).
///
/// Because ClickHouse parses parameters according to the type declared in the
/// SQL (`{id:UInt64}`), any compatible Rust representation works: an `i64` in
/// range works for `UInt8`, and a string works for `Decimal`, `IPv4`, or
/// `DateTime`.
///
/// | Rust | Sent as |
/// |---|---|
/// | integers, floats, `bool` | the number, `true`/`false` |
/// | `&str`, `String` | the text |
/// | `Vec<u8>`, `&[u8]` | the bytes, as a `String` |
/// | [`uuid::Uuid`] | the hyphenated form |
/// | [`chrono::DateTime<Utc>`], [`chrono::NaiveDateTime`] (as UTC) | Unix seconds with a fraction, so no time zone applies |
/// | [`chrono::NaiveDate`] | `YYYY-MM-DD` |
/// | [`std::net::IpAddr`] and its variants | dotted / RFC 5952 text |
/// | `Option<T>` | `T`, or `NULL` for `None` (declare the type `Nullable(…)`) |
/// | `Vec<T>` (`T` not `u8`) | an array |
/// | `HashMap<K, V>`, `BTreeMap<K, V>` | a map |
/// | [`Value`] | the value as it is: the explicit form, for any type |
///
/// Use [`Value`] directly for ClickHouse types without a dedicated Rust type
/// here, such as exact decimals (`Value::Decimal("12.30".into())`) or tuples
/// (`Value::Tuple(vec![1i64.into(), "a".into()])`).
#[derive(Clone, Debug, PartialEq)]
pub struct Param(pub(super) Value);

impl Param {
    /// `NULL`, for a `Nullable(…)` parameter.
    pub fn null() -> Self {
        Param(Value::Null)
    }

    /// The value the parameter is sent as.
    pub fn value(&self) -> &Value {
        &self.0
    }
}

impl From<Value> for Param {
    fn from(v: Value) -> Self {
        Param(v)
    }
}

/// Types that can be elements of a `Vec<T>` array parameter.
///
/// Every parameter type except `u8` implements this trait, because `Vec<u8>` is
/// sent as raw bytes. For an array of `UInt8`, pass `Vec<u16>` or
/// [`Value::Array`].
pub trait ArrayElement: Into<Param> {}

macro_rules! scalar {
    ($($ty:ty => |$v:ident| $make:expr),* $(,)?) => {
        $(
            impl From<$ty> for Param {
                fn from($v: $ty) -> Self {
                    Param($make)
                }
            }
        )*
    };
}

scalar! {
    u8 => |v| Value::UInt(v.into()),
    u16 => |v| Value::UInt(v.into()),
    u32 => |v| Value::UInt(v.into()),
    u64 => |v| Value::UInt(v),
    usize => |v| Value::UInt(v as u64),
    i8 => |v| Value::Int(v.into()),
    i16 => |v| Value::Int(v.into()),
    i32 => |v| Value::Int(v.into()),
    i64 => |v| Value::Int(v),
    isize => |v| Value::Int(v as i64),
    i128 => |v| Value::Int128(v),
    u128 => |v| Value::UInt128(v),
    f32 => |v| Value::Float32(v),
    f64 => |v| Value::Float64(v),
    bool => |v| Value::Bool(v),
    &str => |v| Value::from(v),
    String => |v| Value::from(v),
    &String => |v| Value::from(v.as_str()),
    Vec<u8> => |v| Value::String(v),
    &[u8] => |v| Value::String(v.to_vec()),
    Uuid => |v| Value::Uuid(v),
    DateTime<Utc> => |v| Value::from(v),
    NaiveDateTime => |v| Value::from(v.and_utc()),
    NaiveDate => |v| Value::date(v),
    Ipv4Addr => |v| Value::Ipv4(v),
    Ipv6Addr => |v| Value::Ipv6(v),
    IpAddr => |v| match v {
        IpAddr::V4(ip) => Value::Ipv4(ip),
        IpAddr::V6(ip) => Value::Ipv6(ip),
    },
}

macro_rules! element {
    ($($ty:ty),* $(,)?) => {
        $(impl ArrayElement for $ty {})*
    };
}

element!(
    u16,
    u32,
    u64,
    usize,
    i8,
    i16,
    i32,
    i64,
    isize,
    i128,
    u128,
    f32,
    f64,
    bool,
    &str,
    String,
    &String,
    Vec<u8>,
    &[u8],
    Uuid,
    DateTime<Utc>,
    NaiveDateTime,
    NaiveDate,
    Ipv4Addr,
    Ipv6Addr,
    IpAddr,
    Value,
    Param,
);

impl<T: Into<Param>> ArrayElement for Option<T> {}
impl<T: ArrayElement> ArrayElement for Vec<T> {}
impl<K: Into<Param>, V: Into<Param>, S> ArrayElement for HashMap<K, V, S> {}
impl<K: Into<Param>, V: Into<Param>> ArrayElement for BTreeMap<K, V> {}

impl<T: Into<Param>> From<Option<T>> for Param {
    fn from(v: Option<T>) -> Self {
        v.map_or(Param(Value::Null), Into::into)
    }
}

impl<T: ArrayElement> From<Vec<T>> for Param {
    fn from(v: Vec<T>) -> Self {
        Param(Value::Array(v.into_iter().map(|e| e.into().0).collect()))
    }
}

impl<K: Into<Param>, V: Into<Param>, S> From<HashMap<K, V, S>> for Param {
    fn from(m: HashMap<K, V, S>) -> Self {
        Param(Value::Map(
            m.into_iter()
                .map(|(k, v)| (k.into().0, v.into().0))
                .collect(),
        ))
    }
}

impl<K: Into<Param>, V: Into<Param>> From<BTreeMap<K, V>> for Param {
    fn from(m: BTreeMap<K, V>) -> Self {
        Param(Value::Map(
            m.into_iter()
                .map(|(k, v)| (k.into().0, v.into().0))
                .collect(),
        ))
    }
}