Skip to main content

databend_driver_core/value/
base.rs

1// Copyright 2021 Datafuse Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use databend_client::schema::{DataType, DecimalDataType, DecimalSize, NumberDataType};
16use databend_client::GeometryDataType;
17use ethnum::i256;
18use jiff::Zoned;
19use std::borrow::Cow;
20
21// Thu 1970-01-01 is R.D. 719163
22pub(crate) const DAYS_FROM_CE: i32 = 719_163;
23pub(crate) const TIMESTAMP_FORMAT: &str = "%Y-%m-%d %H:%M:%S%.6f";
24pub(crate) const TIMESTAMP_TIMEZONE_FORMAT: &str = "%Y-%m-%d %H:%M:%S%.6f %z";
25
26#[derive(Clone, Debug, PartialEq)]
27pub enum NumberValue {
28    Int8(i8),
29    Int16(i16),
30    Int32(i32),
31    Int64(i64),
32    UInt8(u8),
33    UInt16(u16),
34    UInt32(u32),
35    UInt64(u64),
36    Float32(f32),
37    Float64(f64),
38    Decimal64(i64, DecimalSize),
39    Decimal128(i128, DecimalSize),
40    Decimal256(i256, DecimalSize),
41}
42
43#[derive(Clone, Debug, PartialEq)]
44pub enum GeoValue {
45    String(String),
46    Binary(Vec<u8>),
47}
48
49impl GeoValue {
50    pub fn from_string(s: String, typ: GeometryDataType) -> crate::error::Result<Self> {
51        match typ {
52            GeometryDataType::WKB | GeometryDataType::EWKB => {
53                Ok(GeoValue::Binary(hex::decode(&s).map_err(|_| {
54                    crate::error::Error::Parsing(format!("fail to unhex {:?} data: {}", typ, s))
55                })?))
56            }
57            _ => Ok(GeoValue::String(s)),
58        }
59    }
60
61    pub fn from_binary(v: Vec<u8>, typ: GeometryDataType) -> crate::error::Result<Self> {
62        match typ {
63            GeometryDataType::WKB | GeometryDataType::EWKB => Ok(GeoValue::Binary(v)),
64            _ => Ok(GeoValue::String(unsafe { String::from_utf8_unchecked(v) })),
65        }
66    }
67
68    pub fn to_string(&self) -> Cow<'_, String> {
69        match self {
70            Self::String(s) => Cow::Borrowed(s),
71            Self::Binary(v) => Cow::Owned(hex::encode_upper(v)),
72        }
73    }
74}
75
76#[derive(Clone, Debug, PartialEq)]
77pub enum Value {
78    Null,
79    EmptyArray,
80    EmptyMap,
81    Boolean(bool),
82    Binary(Vec<u8>),
83    String(String),
84    Number(NumberValue),
85    /// Microseconds from 1970-01-01 00:00:00 UTC
86    Timestamp(Zoned),
87    TimestampTz(Zoned),
88    Date(i32),
89    Array(Vec<Value>),
90    Map(Vec<(Value, Value)>),
91    Tuple(Vec<Value>),
92    Bitmap(String),
93    Variant(String),
94    Geometry(GeoValue),
95    Geography(GeoValue),
96    Interval(String),
97    Vector(Vec<f32>),
98}
99
100impl Value {
101    pub fn get_type(&self) -> DataType {
102        match self {
103            Self::Null => DataType::Null,
104            Self::EmptyArray => DataType::EmptyArray,
105            Self::EmptyMap => DataType::EmptyMap,
106            Self::Boolean(_) => DataType::Boolean,
107            Self::Binary(_) => DataType::Binary,
108            Self::String(_) => DataType::String,
109            Self::Number(n) => match n {
110                NumberValue::Int8(_) => DataType::Number(NumberDataType::Int8),
111                NumberValue::Int16(_) => DataType::Number(NumberDataType::Int16),
112                NumberValue::Int32(_) => DataType::Number(NumberDataType::Int32),
113                NumberValue::Int64(_) => DataType::Number(NumberDataType::Int64),
114                NumberValue::UInt8(_) => DataType::Number(NumberDataType::UInt8),
115                NumberValue::UInt16(_) => DataType::Number(NumberDataType::UInt16),
116                NumberValue::UInt32(_) => DataType::Number(NumberDataType::UInt32),
117                NumberValue::UInt64(_) => DataType::Number(NumberDataType::UInt64),
118                NumberValue::Float32(_) => DataType::Number(NumberDataType::Float32),
119                NumberValue::Float64(_) => DataType::Number(NumberDataType::Float64),
120                NumberValue::Decimal64(_, s) => DataType::Decimal(DecimalDataType::Decimal64(*s)),
121                NumberValue::Decimal128(_, s) => DataType::Decimal(DecimalDataType::Decimal128(*s)),
122                NumberValue::Decimal256(_, s) => DataType::Decimal(DecimalDataType::Decimal256(*s)),
123            },
124            Self::Timestamp(_) => DataType::Timestamp,
125            Self::TimestampTz(_) => DataType::TimestampTz,
126            Self::Date(_) => DataType::Date,
127            Self::Interval(_) => DataType::Interval,
128            Self::Array(vals) => {
129                if vals.is_empty() {
130                    DataType::EmptyArray
131                } else {
132                    DataType::Array(Box::new(vals[0].get_type()))
133                }
134            }
135            Self::Map(kvs) => {
136                if kvs.is_empty() {
137                    DataType::EmptyMap
138                } else {
139                    let inner_ty = DataType::Tuple(vec![kvs[0].0.get_type(), kvs[0].1.get_type()]);
140                    DataType::Map(Box::new(inner_ty))
141                }
142            }
143            Self::Tuple(vals) => {
144                let inner_tys = vals.iter().map(|v| v.get_type()).collect::<Vec<_>>();
145                DataType::Tuple(inner_tys)
146            }
147            Self::Bitmap(_) => DataType::Bitmap,
148            Self::Variant(_) => DataType::Variant,
149            Self::Geometry(_) => DataType::Geometry,
150            Self::Geography(_) => DataType::Geography,
151            Self::Vector(v) => DataType::Vector(v.len() as u64),
152        }
153    }
154}