klickhouse/convert/
mod.rs

1use std::borrow::Cow;
2
3use crate::{types::Type, KlickhouseError, Result, Value};
4
5mod raw_row;
6mod std_deserialize;
7mod std_serialize;
8pub use raw_row::*;
9mod unit_value;
10pub use unit_value::*;
11mod vec_tuple;
12pub use vec_tuple::*;
13#[cfg(feature = "serde")]
14mod json;
15#[cfg(feature = "serde")]
16pub use json::*;
17
18/// A type that can be converted to a raw Clickhouse SQL value.
19pub trait ToSql {
20    fn to_sql(self, type_hint: Option<&Type>) -> Result<Value>;
21}
22
23impl ToSql for Value {
24    fn to_sql(self, _type_hint_: Option<&Type>) -> Result<Value> {
25        Ok(self)
26    }
27}
28
29pub fn unexpected_type(type_: &Type) -> KlickhouseError {
30    KlickhouseError::DeserializeError(format!("unexpected type: {type_}"))
31}
32
33/// A type that can be converted from a raw Clickhouse SQL value.
34pub trait FromSql: Sized {
35    fn from_sql(type_: &Type, value: Value) -> Result<Self>;
36}
37
38impl FromSql for Value {
39    fn from_sql(_type_: &Type, value: Value) -> Result<Self> {
40        Ok(value)
41    }
42}
43
44/// A row that can be deserialized and serialized from a raw Clickhouse SQL value.
45/// Generally this is not implemented manually, but using `klickhouse_derive::Row`.
46/// I.e. `#[derive(klickhouse::Row)]`.
47pub trait Row: Sized {
48    /// If `Some`, `serialize_row` and `deserialize_row` MUST return this number of columns
49    const COLUMN_COUNT: Option<usize>;
50
51    /// If `Some`, `serialize_row` and `deserialize_row` MUST have these names
52    fn column_names() -> Option<Vec<Cow<'static, str>>>;
53
54    fn deserialize_row(map: Vec<(&str, &Type, Value)>) -> Result<Self>;
55
56    fn serialize_row(
57        self,
58        type_hints: &indexmap::IndexMap<String, Type>,
59    ) -> Result<Vec<(Cow<'static, str>, Value)>>;
60}