Skip to main content

tank_core/
value.rs

1use crate::{AsValue, Error, Result, TableRef, interval::Interval};
2use proc_macro2::TokenStream;
3use quote::{ToTokens, quote};
4use rust_decimal::Decimal;
5use serde_json::Value as JsonValue;
6use std::{borrow::Cow, collections::HashMap, hash::Hash, mem::discriminant};
7use time::{Date, OffsetDateTime, PrimitiveDateTime, Time};
8use uuid::Uuid;
9
10/// SQL value representation.
11///
12/// Variants correspond to database column types.
13#[derive(Default, Debug, Clone)]
14pub enum Value {
15    /// SQL NULL.
16    #[default]
17    Null,
18    Boolean(Option<bool>),
19    Int8(Option<i8>),
20    Int16(Option<i16>),
21    Int32(Option<i32>),
22    Int64(Option<i64>),
23    Int128(Option<i128>),
24    UInt8(Option<u8>),
25    UInt16(Option<u16>),
26    UInt32(Option<u32>),
27    UInt64(Option<u64>),
28    UInt128(Option<u128>),
29    Float32(Option<f32>),
30    Float64(Option<f64>),
31    /// Decimal (value, precision, scale).
32    Decimal(Option<Decimal>, u8, u8),
33    Char(Option<char>),
34    Varchar(Option<Cow<'static, str>>),
35    Blob(Option<Box<[u8]>>),
36    Date(Option<Date>),
37    Time(Option<Time>),
38    Timestamp(Option<PrimitiveDateTime>),
39    TimestampWithTimezone(Option<OffsetDateTime>),
40    Interval(Option<Interval>),
41    Uuid(Option<Uuid>),
42    /// Homogeneous array (values, inner type, length).
43    Array(Option<Box<[Value]>>, Box<Value>, u32),
44    /// Variable-length list (values, inner type).
45    List(Option<Vec<Value>>, Box<Value>),
46    /// Map (entries, key type, value type).
47    Map(Option<HashMap<Value, Value>>, Box<Value>, Box<Value>),
48    Json(Option<JsonValue>),
49    /// Named struct (fields, field types, type name).
50    Struct(Option<Vec<(String, Value)>>, Vec<(String, Value)>, TableRef),
51    /// Unknown type (usually used when no further information is available).
52    Unknown(Option<String>),
53}
54
55impl Value {
56    pub fn same_type(&self, other: &Self) -> bool {
57        match (self, other) {
58            (Self::Decimal(.., l_width, l_scale), Self::Decimal(.., r_width, r_scale)) => {
59                (*l_width == 0 || *r_width == 0 || l_width == r_width)
60                    && (*l_scale == 0 || *r_scale == 0 || l_scale == r_scale)
61            }
62            (Self::Array(.., l_type, l_len), Self::Array(.., r_type, r_len)) => {
63                l_len == r_len && l_type.same_type(&r_type)
64            }
65            (Self::List(.., l), Self::List(.., r)) => l.same_type(r),
66            (Self::Map(.., l_key, l_value), Self::Map(.., r_key, r_value)) => {
67                l_key.same_type(r_key) && l_value.same_type(&r_value)
68            }
69            _ => discriminant(self) == discriminant(other),
70        }
71    }
72
73    pub fn is_null(&self) -> bool {
74        match self {
75            Value::Null
76            | Value::Boolean(None, ..)
77            | Value::Int8(None, ..)
78            | Value::Int16(None, ..)
79            | Value::Int32(None, ..)
80            | Value::Int64(None, ..)
81            | Value::Int128(None, ..)
82            | Value::UInt8(None, ..)
83            | Value::UInt16(None, ..)
84            | Value::UInt32(None, ..)
85            | Value::UInt64(None, ..)
86            | Value::UInt128(None, ..)
87            | Value::Float32(None, ..)
88            | Value::Float64(None, ..)
89            | Value::Decimal(None, ..)
90            | Value::Char(None, ..)
91            | Value::Varchar(None, ..)
92            | Value::Blob(None, ..)
93            | Value::Date(None, ..)
94            | Value::Time(None, ..)
95            | Value::Timestamp(None, ..)
96            | Value::TimestampWithTimezone(None, ..)
97            | Value::Interval(None, ..)
98            | Value::Uuid(None, ..)
99            | Value::Array(None, ..)
100            | Value::List(None, ..)
101            | Value::Map(None, ..)
102            | Value::Json(None, ..)
103            | Value::Json(Some(serde_json::Value::Null), ..)
104            | Value::Struct(None, ..)
105            | Value::Unknown(None, ..) => true,
106            _ => false,
107        }
108    }
109
110    pub fn as_null(&self) -> Value {
111        match self {
112            Value::Null => Value::Null,
113            Value::Boolean(..) => Value::Boolean(None),
114            Value::Int8(..) => Value::Int8(None),
115            Value::Int16(..) => Value::Int16(None),
116            Value::Int32(..) => Value::Int32(None),
117            Value::Int64(..) => Value::Int64(None),
118            Value::Int128(..) => Value::Int128(None),
119            Value::UInt8(..) => Value::UInt8(None),
120            Value::UInt16(..) => Value::UInt16(None),
121            Value::UInt32(..) => Value::UInt32(None),
122            Value::UInt64(..) => Value::UInt64(None),
123            Value::UInt128(..) => Value::UInt128(None),
124            Value::Float32(..) => Value::Float32(None),
125            Value::Float64(..) => Value::Float64(None),
126            Value::Decimal(.., w, s) => Value::Decimal(None, *w, *s),
127            Value::Char(..) => Value::Char(None),
128            Value::Varchar(..) => Value::Varchar(None),
129            Value::Blob(..) => Value::Blob(None),
130            Value::Date(..) => Value::Date(None),
131            Value::Time(..) => Value::Time(None),
132            Value::Timestamp(..) => Value::Timestamp(None),
133            Value::TimestampWithTimezone(..) => Value::TimestampWithTimezone(None),
134            Value::Interval(..) => Value::Interval(None),
135            Value::Uuid(..) => Value::Uuid(None),
136            Value::Array(.., t, len) => Value::Array(None, t.clone(), *len),
137            Value::List(.., t) => Value::List(None, t.clone()),
138            Value::Map(.., k, v) => Value::Map(None, k.clone(), v.clone()),
139            Value::Json(..) => Value::Json(None),
140            Value::Struct(.., ty, name) => Value::Struct(None, ty.clone(), name.clone()),
141            Value::Unknown(..) => Value::Unknown(None),
142        }
143    }
144
145    pub fn try_as(self, value: &Value) -> Result<Value> {
146        if self.same_type(value) {
147            return Ok(self);
148        }
149        match value {
150            Value::Boolean(..) => bool::try_from_value(self).map(AsValue::as_value),
151            Value::Int8(..) => i8::try_from_value(self).map(AsValue::as_value),
152            Value::Int16(..) => i16::try_from_value(self).map(AsValue::as_value),
153            Value::Int32(..) => i32::try_from_value(self).map(AsValue::as_value),
154            Value::Int64(..) => i64::try_from_value(self).map(AsValue::as_value),
155            Value::Int128(..) => i128::try_from_value(self).map(AsValue::as_value),
156            Value::UInt8(..) => u8::try_from_value(self).map(AsValue::as_value),
157            Value::UInt16(..) => u16::try_from_value(self).map(AsValue::as_value),
158            Value::UInt32(..) => u32::try_from_value(self).map(AsValue::as_value),
159            Value::UInt64(..) => u64::try_from_value(self).map(AsValue::as_value),
160            Value::UInt128(..) => u128::try_from_value(self).map(AsValue::as_value),
161            Value::Float32(..) => f32::try_from_value(self).map(AsValue::as_value),
162            Value::Float64(..) => f64::try_from_value(self).map(AsValue::as_value),
163            Value::Decimal(..) => Decimal::try_from_value(self).map(AsValue::as_value),
164            Value::Char(..) => char::try_from_value(self).map(AsValue::as_value),
165            Value::Varchar(..) => String::try_from_value(self).map(AsValue::as_value),
166            Value::Blob(..) => Box::<[u8]>::try_from_value(self).map(AsValue::as_value),
167            Value::Date(..) => Date::try_from_value(self).map(AsValue::as_value),
168            Value::Time(..) => Time::try_from_value(self).map(AsValue::as_value),
169            Value::Timestamp(..) => PrimitiveDateTime::try_from_value(self).map(AsValue::as_value),
170            Value::TimestampWithTimezone(..) => {
171                OffsetDateTime::try_from_value(self).map(AsValue::as_value)
172            }
173            Value::Interval(..) => Interval::try_from_value(self).map(AsValue::as_value),
174            Value::Uuid(..) => Uuid::try_from_value(self).map(AsValue::as_value),
175            // Value::Array(.., ty, len) => {
176            //     Box::<[Value]>::try_from_value(self).map(AsValue::as_value)
177            // }
178            // Value::List(..) => Box::<[Value]>::try_from_value(self).map(AsValue::as_value),
179            // Value::Map(..) => Date::try_from_value(self).map(AsValue::as_value),
180            _ => {
181                return Err(Error::msg(format!(
182                    "Cannot convert value {:?} into value {:?}",
183                    self, value
184                )));
185            }
186        }
187    }
188}
189
190impl PartialEq for Value {
191    fn eq(&self, other: &Self) -> bool {
192        match (self, other) {
193            (Self::Boolean(l), Self::Boolean(r)) => l == r,
194            (Self::Int8(l), Self::Int8(r)) => l == r,
195            (Self::Int16(l), Self::Int16(r)) => l == r,
196            (Self::Int32(l), Self::Int32(r)) => l == r,
197            (Self::Int64(l), Self::Int64(r)) => l == r,
198            (Self::Int128(l), Self::Int128(r)) => l == r,
199            (Self::UInt8(l), Self::UInt8(r)) => l == r,
200            (Self::UInt16(l), Self::UInt16(r)) => l == r,
201            (Self::UInt32(l), Self::UInt32(r)) => l == r,
202            (Self::UInt64(l), Self::UInt64(r)) => l == r,
203            (Self::UInt128(l), Self::UInt128(r)) => l == r,
204            (Self::Float32(l), Self::Float32(r)) => {
205                l == r
206                    || l.and_then(|l| r.and_then(|r| Some(l.is_nan() && r.is_nan())))
207                        .unwrap_or_default()
208            }
209            (Self::Float64(l), Self::Float64(r)) => {
210                l == r
211                    || l.and_then(|l| r.and_then(|r| Some(l.is_nan() && r.is_nan())))
212                        .unwrap_or_default()
213            }
214            (Self::Decimal(l, l_width, l_scale), Self::Decimal(r, r_width, r_scale)) => {
215                l == r && l_width == r_width && l_scale == r_scale
216            }
217            (Self::Char(l), Self::Char(r)) => l == r,
218            (Self::Varchar(l), Self::Varchar(r)) => l == r,
219            (Self::Blob(l), Self::Blob(r)) => l == r,
220            (Self::Date(l), Self::Date(r)) => l == r,
221            (Self::Time(l), Self::Time(r)) => l == r,
222            (Self::Timestamp(l), Self::Timestamp(r)) => l == r,
223            (Self::TimestampWithTimezone(l), Self::TimestampWithTimezone(r)) => l == r,
224            (Self::Interval(l), Self::Interval(r)) => l == r,
225            (Self::Uuid(l), Self::Uuid(r)) => l == r,
226            (Self::Array(l, ..), Self::Array(r, ..)) => l == r && self.same_type(other),
227            (Self::List(l, ..), Self::List(r, ..)) => l == r && self.same_type(other),
228            (Self::Map(None, ..), Self::Map(None, ..)) => self.same_type(other),
229            (Self::Map(Some(l), ..), Self::Map(Some(r), ..)) => {
230                l.is_empty() == r.is_empty() && self.same_type(other)
231            }
232            (Self::Map(..), Self::Map(..)) => self.same_type(other),
233            (Self::Json(l), Self::Json(r)) => l == r,
234            (Self::Struct(l, l_ty, l_name), Self::Struct(r, r_ty, r_name)) => {
235                l_name == r_name && l == r && l_ty == r_ty
236            }
237            (Self::Unknown(..), Self::Unknown(..)) => false,
238            _ => false,
239        }
240    }
241}
242
243impl Eq for Value {}
244
245impl Hash for Value {
246    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
247        use Value::*;
248        discriminant(self).hash(state);
249        match self {
250            Null => {}
251            Boolean(v) => v.hash(state),
252            Int8(v) => v.hash(state),
253            Int16(v) => v.hash(state),
254            Int32(v) => v.hash(state),
255            Int64(v) => v.hash(state),
256            Int128(v) => v.hash(state),
257
258            UInt8(v) => v.hash(state),
259            UInt16(v) => v.hash(state),
260            UInt32(v) => v.hash(state),
261            UInt64(v) => v.hash(state),
262            UInt128(v) => v.hash(state),
263            Float32(Some(v)) => {
264                v.to_bits().hash(state);
265            }
266            Float32(None) => None::<u32>.hash(state),
267            Float64(Some(v)) => {
268                v.to_bits().hash(state);
269            }
270            Float64(None) => None::<u64>.hash(state),
271            Decimal(v, width, scale) => {
272                v.hash(state);
273                width.hash(state);
274                scale.hash(state);
275            }
276            Char(v) => v.hash(state),
277            Varchar(v) => v.hash(state),
278            Blob(v) => v.hash(state),
279            Date(v) => v.hash(state),
280            Time(v) => v.hash(state),
281            Timestamp(v) => v.hash(state),
282            TimestampWithTimezone(v) => v.hash(state),
283            Interval(v) => v.hash(state),
284            Uuid(v) => v.hash(state),
285            Array(v, typ, len) => {
286                v.hash(state);
287                typ.hash(state);
288                len.hash(state);
289            }
290            List(v, typ) => {
291                v.hash(state);
292                typ.hash(state);
293            }
294            Map(v, key, val) => {
295                match v {
296                    Some(map) => {
297                        for (key, val) in map {
298                            key.hash(state);
299                            val.hash(state);
300                        }
301                    }
302                    None => {}
303                }
304                key.hash(state);
305                val.hash(state);
306            }
307            Json(v) => v.hash(state),
308            Struct(v, t, name) => {
309                match v {
310                    Some(v) => v.hash(state),
311                    None => {}
312                }
313                t.hash(state);
314                name.hash(state);
315            }
316            Unknown(v) => v.hash(state),
317        }
318    }
319}
320
321/// Internally decoded type info for macros.
322#[derive(Default)]
323pub struct TypeDecoded {
324    /// Representative value establishing variant & metadata.
325    pub value: Value,
326    /// Nullability indicator.
327    pub nullable: bool,
328    /// Passive flag (exclude from INSERT column/value list).
329    pub passive: bool,
330}
331
332pub type CheckPassive = Box<dyn Fn(TokenStream) -> TokenStream>;
333
334impl ToTokens for Value {
335    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
336        let ts = match self {
337            Value::Null => quote!(::tank::Value::Null),
338            Value::Boolean(..) => quote!(::tank::Value::Boolean(None)),
339            Value::Int8(..) => quote!(::tank::Value::Int8(None)),
340            Value::Int16(..) => quote!(::tank::Value::Int16(None)),
341            Value::Int32(..) => quote!(::tank::Value::Int32(None)),
342            Value::Int64(..) => quote!(::tank::Value::Int64(None)),
343            Value::Int128(..) => quote!(::tank::Value::Int128(None)),
344            Value::UInt8(..) => quote!(::tank::Value::UInt8(None)),
345            Value::UInt16(..) => quote!(::tank::Value::UInt16(None)),
346            Value::UInt32(..) => quote!(::tank::Value::UInt32(None)),
347            Value::UInt64(..) => quote!(::tank::Value::UInt64(None)),
348            Value::UInt128(..) => quote!(::tank::Value::UInt128(None)),
349            Value::Float32(..) => quote!(::tank::Value::Float32(None)),
350            Value::Float64(..) => quote!(::tank::Value::Float64(None)),
351            Value::Decimal(.., width, scale) => {
352                quote!(::tank::Value::Decimal(None, #width, #scale))
353            }
354            Value::Char(..) => quote!(tank::Value::Char(None)),
355            Value::Varchar(..) => quote!(::tank::Value::Varchar(None)),
356            Value::Blob(..) => quote!(::tank::Value::Blob(None)),
357            Value::Date(..) => quote!(::tank::Value::Date(None)),
358            Value::Time(..) => quote!(::tank::Value::Time(None)),
359            Value::Timestamp(..) => quote!(::tank::Value::Timestamp(None)),
360            Value::TimestampWithTimezone(..) => quote!(::tank::Value::TimestampWithTimezone(None)),
361            Value::Interval(..) => quote!(::tank::Value::Interval(None)),
362            Value::Uuid(..) => quote!(::tank::Value::Uuid(None)),
363            Value::Array(.., inner, size) => {
364                quote!(::tank::Value::Array(None, Box::new(#inner), #size))
365            }
366            Value::List(.., inner) => {
367                let inner = inner.as_ref().to_token_stream();
368                quote!(::tank::Value::List(None, Box::new(#inner)))
369            }
370            Value::Map(.., key, value) => {
371                let key = key.as_ref().to_token_stream();
372                let value = value.as_ref().to_token_stream();
373                quote!(::tank::Value::Map(None, Box::new(#key), Box::new(#value)))
374            }
375            Value::Json(..) => quote!(::tank::Value::Json(None)),
376            Value::Struct(.., ty, name) => {
377                let values = ty.into_iter().map(|(k, v)| quote!((#k.into(), #v)));
378                quote!(::tank::Value::Struct(None, vec!(#(#values),*), #name))
379            }
380            Value::Unknown(..) => quote!(::tank::Value::Unknown(None)),
381        };
382        tokens.extend(ts);
383    }
384}