clickhouse_arrow/native/
convert.rs

1use std::borrow::Cow;
2
3use crate::{Error, Result, Type, Value};
4
5pub mod raw_row;
6pub mod std_deserialize;
7pub mod std_serialize;
8pub use raw_row::*;
9pub mod unit_value;
10
11/// Type alias for the definition of a column for schema creation
12pub type ColumnDefinition<T = Value> = (String, Type, Option<T>);
13
14/// A type that can be converted to a raw `ClickHouse` SQL value.
15pub trait ToSql {
16    /// # Errors
17    fn to_sql(self, type_hint: Option<&Type>) -> Result<Value>;
18}
19
20impl ToSql for Value {
21    fn to_sql(self, _type_hint_: Option<&Type>) -> Result<Value> { Ok(self) }
22}
23
24pub fn unexpected_type(type_: &Type) -> Error {
25    Error::DeserializeError(format!("unexpected type: {type_}"))
26}
27
28/// A type that can be converted from a raw `ClickHouse` SQL value.
29pub trait FromSql: Sized {
30    /// # Errors
31    fn from_sql(type_: &Type, value: Value) -> Result<Self>;
32}
33
34impl FromSql for Value {
35    fn from_sql(_type_: &Type, value: Value) -> Result<Self> { Ok(value) }
36}
37
38/// A row that can be deserialized and serialized from a raw `ClickHouse` SQL value.
39/// Generally this is not implemented manually, but using `clickhouse_arrow_derive::Row`,
40/// i.e. `#[derive(clickhouse_arrow::Row)]`.
41///
42/// # Example
43/// ```rust,ignore
44/// use clickhouse_arrow::Row;
45/// #[derive(Row)]
46/// struct MyRow {
47///     id: String,
48///     name: String,
49///     age: u8
50/// }
51/// ```
52pub trait Row: Sized {
53    /// If `Some`, `serialize_row` and `deserialize_row` MUST return this number of columns
54    const COLUMN_COUNT: Option<usize>;
55
56    /// If `Some`, `serialize_row` and `deserialize_row` MUST have these names
57    fn column_names() -> Option<Vec<Cow<'static, str>>>;
58
59    /// Infers the schema and returns it.
60    fn to_schema() -> Option<Vec<ColumnDefinition<Value>>>;
61
62    /// # Errors
63    fn deserialize_row(map: Vec<(&str, &Type, Value)>) -> Result<Self>;
64
65    /// # Errors
66    fn serialize_row(
67        self,
68        type_hints: &[(String, Type)],
69    ) -> Result<Vec<(Cow<'static, str>, Value)>>;
70}