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