gluesql_core/data/
value.rs

1use {
2    super::{Interval, Key, StringExt},
3    crate::{
4        ast::{DataType, DateTimeField},
5        data::point::Point,
6        result::Result,
7    },
8    binary_op::TryBinaryOperator,
9    chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike},
10    core::ops::Sub,
11    rust_decimal::Decimal,
12    serde::{Deserialize, Serialize},
13    std::{
14        cmp::Ordering,
15        collections::BTreeMap,
16        fmt::Debug,
17        hash::{Hash, Hasher},
18        mem::discriminant,
19        net::IpAddr,
20    },
21    utils::Tribool,
22};
23
24mod binary_op;
25mod convert;
26mod date;
27mod error;
28mod json;
29mod selector;
30mod to_sql;
31mod uuid;
32
33pub use {
34    error::{NumericBinaryOperator, ValueError},
35    json::BTreeMapJsonExt,
36};
37
38pub(crate) use {
39    date::{parse_date, parse_time, parse_timestamp},
40    uuid::parse_uuid,
41};
42
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub enum Value {
45    Bool(bool),
46    I8(i8),
47    I16(i16),
48    I32(i32),
49    I64(i64),
50    I128(i128),
51    U8(u8),
52    U16(u16),
53    U32(u32),
54    U64(u64),
55    U128(u128),
56    F32(f32),
57    F64(f64),
58    Decimal(Decimal),
59    Str(String),
60    Bytea(Vec<u8>),
61    Inet(IpAddr),
62    Date(NaiveDate),
63    Timestamp(NaiveDateTime),
64    Time(NaiveTime),
65    Interval(Interval),
66    Uuid(u128),
67    Map(BTreeMap<String, Value>),
68    List(Vec<Value>),
69    Point(Point),
70    Null,
71}
72
73impl From<Tribool> for Value {
74    fn from(t: Tribool) -> Self {
75        match t {
76            Tribool::True => Value::Bool(true),
77            Tribool::False => Value::Bool(false),
78            Tribool::Null => Value::Null,
79        }
80    }
81}
82
83impl Value {
84    pub fn evaluate_eq(&self, other: &Value) -> Tribool {
85        use Value::*;
86        match (self, other) {
87            (Null, _) | (_, Null) => Tribool::Null,
88            (I8(l), _) => Tribool::from(l == other),
89            (I16(l), _) => Tribool::from(l == other),
90            (I32(l), _) => Tribool::from(l == other),
91            (I64(l), _) => Tribool::from(l == other),
92            (I128(l), _) => Tribool::from(l == other),
93            (U8(l), _) => Tribool::from(l == other),
94            (U16(l), _) => Tribool::from(l == other),
95            (U32(l), _) => Tribool::from(l == other),
96            (U64(l), _) => Tribool::from(l == other),
97            (U128(l), _) => Tribool::from(l == other),
98            (F32(l), _) => Tribool::from(l == other),
99            (F64(l), _) => Tribool::from(l == other),
100            (Date(l), Timestamp(r)) => Tribool::from(
101                l.and_hms_opt(0, 0, 0)
102                    .is_some_and(|date_time| &date_time == r),
103            ),
104            (Timestamp(l), Date(r)) => Tribool::from(
105                r.and_hms_opt(0, 0, 0)
106                    .is_some_and(|date_time| l == &date_time),
107            ),
108            _ => Tribool::from(self == other),
109        }
110    }
111
112    pub fn evaluate_cmp(&self, other: &Value) -> Option<Ordering> {
113        match (self, other) {
114            (Value::I8(l), _) => l.partial_cmp(other),
115            (Value::I16(l), _) => l.partial_cmp(other),
116            (Value::I32(l), _) => l.partial_cmp(other),
117            (Value::I64(l), _) => l.partial_cmp(other),
118            (Value::I128(l), _) => l.partial_cmp(other),
119            (Value::U8(l), _) => l.partial_cmp(other),
120            (Value::U16(l), _) => l.partial_cmp(other),
121            (Value::U32(l), _) => l.partial_cmp(other),
122            (Value::U64(l), _) => l.partial_cmp(other),
123            (Value::U128(l), _) => l.partial_cmp(other),
124            (Value::F32(l), _) => l.partial_cmp(other),
125            (Value::F64(l), _) => l.partial_cmp(other),
126            (Value::Decimal(l), Value::Decimal(r)) => Some(l.cmp(r)),
127            (Value::Bool(l), Value::Bool(r)) => Some(l.cmp(r)),
128            (Value::Str(l), Value::Str(r)) => Some(l.cmp(r)),
129            (Value::Bytea(l), Value::Bytea(r)) => Some(l.cmp(r)),
130            (Value::Inet(l), Value::Inet(r)) => Some(l.cmp(r)),
131            (Value::Date(l), Value::Date(r)) => Some(l.cmp(r)),
132            (Value::Date(l), Value::Timestamp(r)) => {
133                l.and_hms_opt(0, 0, 0).map(|date_time| date_time.cmp(r))
134            }
135            (Value::Timestamp(l), Value::Date(r)) => {
136                r.and_hms_opt(0, 0, 0).map(|date_time| l.cmp(&date_time))
137            }
138            (Value::Timestamp(l), Value::Timestamp(r)) => Some(l.cmp(r)),
139            (Value::Time(l), Value::Time(r)) => Some(l.cmp(r)),
140            (Value::Interval(l), Value::Interval(r)) => l.partial_cmp(r),
141            (Value::Uuid(l), Value::Uuid(r)) => Some(l.cmp(r)),
142            _ => None,
143        }
144    }
145
146    pub fn is_zero(&self) -> bool {
147        match self {
148            Value::I8(v) => *v == 0,
149            Value::I16(v) => *v == 0,
150            Value::I32(v) => *v == 0,
151            Value::I64(v) => *v == 0,
152            Value::I128(v) => *v == 0,
153            Value::U8(v) => *v == 0,
154            Value::U16(v) => *v == 0,
155            Value::U32(v) => *v == 0,
156            Value::U64(v) => *v == 0,
157            Value::U128(v) => *v == 0,
158            Value::F32(v) => *v == 0.0,
159            Value::F64(v) => *v == 0.0,
160            Value::Decimal(v) => *v == Decimal::ZERO,
161            _ => false,
162        }
163    }
164
165    pub fn get_type(&self) -> Option<DataType> {
166        match self {
167            Value::I8(_) => Some(DataType::Int8),
168            Value::I16(_) => Some(DataType::Int16),
169            Value::I32(_) => Some(DataType::Int32),
170            Value::I64(_) => Some(DataType::Int),
171            Value::I128(_) => Some(DataType::Int128),
172            Value::U8(_) => Some(DataType::Uint8),
173            Value::U16(_) => Some(DataType::Uint16),
174            Value::U32(_) => Some(DataType::Uint32),
175            Value::U64(_) => Some(DataType::Uint64),
176            Value::U128(_) => Some(DataType::Uint128),
177            Value::F32(_) => Some(DataType::Float32),
178            Value::F64(_) => Some(DataType::Float),
179            Value::Decimal(_) => Some(DataType::Decimal),
180            Value::Bool(_) => Some(DataType::Boolean),
181            Value::Str(_) => Some(DataType::Text),
182            Value::Bytea(_) => Some(DataType::Bytea),
183            Value::Inet(_) => Some(DataType::Inet),
184            Value::Date(_) => Some(DataType::Date),
185            Value::Timestamp(_) => Some(DataType::Timestamp),
186            Value::Time(_) => Some(DataType::Time),
187            Value::Interval(_) => Some(DataType::Interval),
188            Value::Uuid(_) => Some(DataType::Uuid),
189            Value::Map(_) => Some(DataType::Map),
190            Value::List(_) => Some(DataType::List),
191            Value::Point(_) => Some(DataType::Point),
192            Value::Null => None,
193        }
194    }
195
196    pub fn validate_type(&self, data_type: &DataType) -> Result<()> {
197        let valid = self.get_type().is_none_or(|t| t == *data_type);
198
199        if !valid {
200            return Err(ValueError::IncompatibleDataType {
201                data_type: data_type.clone(),
202                value: self.clone(),
203            }
204            .into());
205        }
206
207        Ok(())
208    }
209
210    pub fn validate_null(&self, nullable: bool) -> Result<()> {
211        if !nullable && matches!(self, Value::Null) {
212            return Err(ValueError::NullValueOnNotNullField.into());
213        }
214
215        Ok(())
216    }
217
218    pub fn cast(&self, data_type: &DataType) -> Result<Self> {
219        match (data_type, self) {
220            (DataType::Int8, Value::I8(_))
221            | (DataType::Int16, Value::I16(_))
222            | (DataType::Int32, Value::I32(_))
223            | (DataType::Int, Value::I64(_))
224            | (DataType::Int128, Value::I128(_))
225            | (DataType::Uint8, Value::U8(_))
226            | (DataType::Uint16, Value::U16(_))
227            | (DataType::Uint32, Value::U32(_))
228            | (DataType::Uint64, Value::U64(_))
229            | (DataType::Uint128, Value::U128(_))
230            | (DataType::Float32, Value::F32(_))
231            | (DataType::Float, Value::F64(_))
232            | (DataType::Decimal, Value::Decimal(_))
233            | (DataType::Boolean, Value::Bool(_))
234            | (DataType::Text, Value::Str(_))
235            | (DataType::Bytea, Value::Bytea(_))
236            | (DataType::Inet, Value::Inet(_))
237            | (DataType::Point, Value::Point(_))
238            | (DataType::Date, Value::Date(_))
239            | (DataType::Timestamp, Value::Timestamp(_))
240            | (DataType::Time, Value::Time(_))
241            | (DataType::Interval, Value::Interval(_))
242            | (DataType::Uuid, Value::Uuid(_)) => Ok(self.clone()),
243
244            (_, Value::Null) => Ok(Value::Null),
245
246            (DataType::Boolean, value) => Ok(value.try_into().map(Value::Bool)?),
247            (DataType::Int8, value) => Ok(value.try_into().map(Value::I8)?),
248            (DataType::Int16, value) => Ok(value.try_into().map(Value::I16)?),
249            (DataType::Int32, value) => Ok(value.try_into().map(Value::I32)?),
250            (DataType::Int, value) => Ok(value.try_into().map(Value::I64)?),
251            (DataType::Int128, value) => Ok(value.try_into().map(Value::I128)?),
252            (DataType::Uint8, value) => Ok(value.try_into().map(Value::U8)?),
253            (DataType::Uint16, value) => Ok(value.try_into().map(Value::U16)?),
254            (DataType::Uint32, value) => Ok(value.try_into().map(Value::U32)?),
255            (DataType::Uint64, value) => Ok(value.try_into().map(Value::U64)?),
256            (DataType::Uint128, value) => Ok(value.try_into().map(Value::U128)?),
257            (DataType::Float32, value) => Ok(value.try_into().map(Value::F32)?),
258            (DataType::Float, value) => Ok(value.try_into().map(Value::F64)?),
259            (DataType::Decimal, value) => Ok(value.try_into().map(Value::Decimal)?),
260
261            (DataType::Text, value) => Ok(Value::Str(value.into())),
262
263            (DataType::Date, value) => Ok(value.try_into().map(Value::Date)?),
264            (DataType::Time, value) => Ok(value.try_into().map(Value::Time)?),
265            (DataType::Timestamp, value) => Ok(value.try_into().map(Value::Timestamp)?),
266
267            (DataType::Interval, Value::Str(value)) => Interval::parse(value).map(Value::Interval),
268            (DataType::Uuid, Value::Str(value)) => uuid::parse_uuid(value).map(Value::Uuid),
269
270            (DataType::Uuid, value) => Ok(value.try_into().map(Value::Uuid)?),
271            (DataType::Inet, value) => Ok(value.try_into().map(Value::Inet)?),
272            (DataType::Point, value) => Ok(value.try_into().map(Value::Point)?),
273
274            (DataType::Bytea, Value::Str(value)) => hex::decode(value)
275                .map_err(|_| ValueError::CastFromHexToByteaFailed(value.clone()).into())
276                .map(Value::Bytea),
277            (DataType::List, Value::Str(value)) => Self::parse_json_list(value),
278            (DataType::Map, Value::Str(value)) => Self::parse_json_map(value),
279
280            _ => Err(ValueError::UnimplementedCast {
281                value: self.clone(),
282                data_type: data_type.clone(),
283            }
284            .into()),
285        }
286    }
287
288    #[must_use]
289    pub fn concat(self, other: Value) -> Value {
290        match (self, other) {
291            (Value::Null, _) | (_, Value::Null) => Value::Null,
292            (Value::List(l), Value::List(r)) => Value::List([l, r].concat()),
293            (l, r) => Value::Str(String::from(l) + &String::from(r)),
294        }
295    }
296
297    pub fn add(&self, other: &Value) -> Result<Value> {
298        use Value::*;
299
300        match (self, other) {
301            (I8(a), b) => a.try_add(b),
302            (I16(a), b) => a.try_add(b),
303            (I32(a), b) => a.try_add(b),
304            (I64(a), b) => a.try_add(b),
305            (I128(a), b) => a.try_add(b),
306            (U8(a), b) => a.try_add(b),
307            (U16(a), b) => a.try_add(b),
308            (U32(a), b) => a.try_add(b),
309            (U64(a), b) => a.try_add(b),
310            (U128(a), b) => a.try_add(b),
311            (F32(a), b) => a.try_add(b),
312            (F64(a), b) => a.try_add(b),
313            (Decimal(a), b) => a.try_add(b),
314            (Date(a), Time(b)) => Ok(Timestamp(NaiveDateTime::new(*a, *b))),
315            (Date(a), Interval(b)) => b.add_date(a).map(Timestamp),
316            (Timestamp(a), Interval(b)) => b.add_timestamp(a).map(Timestamp),
317            (Time(a), Interval(b)) => b.add_time(a).map(Time),
318            (Interval(a), Interval(b)) => a.add(b).map(Interval),
319            (
320                Null,
321                I8(_) | I16(_) | I32(_) | I64(_) | I128(_) | U8(_) | U16(_) | U32(_) | U64(_)
322                | U128(_) | F32(_) | F64(_) | Decimal(_) | Date(_) | Timestamp(_) | Interval(_)
323                | Null,
324            )
325            | (Date(_) | Timestamp(_) | Time(_) | Interval(_), Null) => Ok(Null),
326            _ => Err(ValueError::NonNumericMathOperation {
327                lhs: self.clone(),
328                operator: NumericBinaryOperator::Add,
329                rhs: other.clone(),
330            }
331            .into()),
332        }
333    }
334
335    pub fn subtract(&self, other: &Value) -> Result<Value> {
336        use {super::Interval as I, Value::*};
337
338        match (self, other) {
339            (I8(a), _) => a.try_subtract(other),
340            (I16(a), _) => a.try_subtract(other),
341            (I32(a), _) => a.try_subtract(other),
342            (I64(a), _) => a.try_subtract(other),
343            (I128(a), _) => a.try_subtract(other),
344            (U8(a), _) => a.try_subtract(other),
345            (U16(a), _) => a.try_subtract(other),
346            (U32(a), _) => a.try_subtract(other),
347            (U64(a), _) => a.try_subtract(other),
348            (U128(a), _) => a.try_subtract(other),
349            (F32(a), _) => a.try_subtract(other),
350            (F64(a), _) => a.try_subtract(other),
351            (Decimal(a), _) => a.try_subtract(other),
352            (Date(a), Date(b)) => Ok(Interval(I::days((*a - *b).num_days() as i32))),
353            (Date(a), Interval(b)) => b.subtract_from_date(a).map(Timestamp),
354            (Timestamp(a), Interval(b)) => b.subtract_from_timestamp(a).map(Timestamp),
355            (Timestamp(a), Timestamp(b)) => a
356                .sub(*b)
357                .num_microseconds()
358                .ok_or_else(|| {
359                    ValueError::UnreachableIntegerOverflow(format!("{a:?} - {b:?}")).into()
360                })
361                .map(|v| Interval(I::microseconds(v))),
362            (Time(a), Time(b)) => a
363                .sub(*b)
364                .num_microseconds()
365                .ok_or_else(|| {
366                    ValueError::UnreachableIntegerOverflow(format!("{a:?} - {b:?}")).into()
367                })
368                .map(|v| Interval(I::microseconds(v))),
369            (Time(a), Interval(b)) => b.subtract_from_time(a).map(Time),
370            (Interval(a), Interval(b)) => a.subtract(b).map(Interval),
371            (
372                Null,
373                I8(_) | I16(_) | I32(_) | I64(_) | I128(_) | U8(_) | U16(_) | U32(_) | U64(_)
374                | U128(_) | F32(_) | F64(_) | Decimal(_) | Date(_) | Timestamp(_) | Time(_)
375                | Interval(_) | Null,
376            )
377            | (Date(_) | Timestamp(_) | Time(_) | Interval(_), Null) => Ok(Null),
378            _ => Err(ValueError::NonNumericMathOperation {
379                lhs: self.clone(),
380                operator: NumericBinaryOperator::Subtract,
381                rhs: other.clone(),
382            }
383            .into()),
384        }
385    }
386
387    pub fn multiply(&self, other: &Value) -> Result<Value> {
388        use Value::*;
389
390        match (self, other) {
391            (I8(a), _) => a.try_multiply(other),
392            (I16(a), _) => a.try_multiply(other),
393            (I32(a), _) => a.try_multiply(other),
394            (I64(a), _) => a.try_multiply(other),
395            (I128(a), _) => a.try_multiply(other),
396            (U8(a), _) => a.try_multiply(other),
397            (U16(a), _) => a.try_multiply(other),
398            (U32(a), _) => a.try_multiply(other),
399            (U64(a), _) => a.try_multiply(other),
400            (U128(a), _) => a.try_multiply(other),
401            (F32(a), _) => a.try_multiply(other),
402            (F64(a), _) => a.try_multiply(other),
403            (Decimal(a), _) => a.try_multiply(other),
404            (Interval(a), I8(b)) => Ok(Interval(*a * *b)),
405            (Interval(a), I16(b)) => Ok(Interval(*a * *b)),
406            (Interval(a), I32(b)) => Ok(Interval(*a * *b)),
407            (Interval(a), I64(b)) => Ok(Interval(*a * *b)),
408            (Interval(a), I128(b)) => Ok(Interval(*a * *b)),
409            (Interval(a), F32(b)) => Ok(Interval(*a * *b)),
410            (Interval(a), F64(b)) => Ok(Interval(*a * *b)),
411            (
412                Null,
413                I8(_) | I16(_) | I32(_) | I64(_) | I128(_) | U8(_) | U16(_) | U32(_) | U64(_)
414                | U128(_) | F32(_) | F64(_) | Decimal(_) | Interval(_) | Null,
415            )
416            | (Interval(_), Null) => Ok(Null),
417            _ => Err(ValueError::NonNumericMathOperation {
418                lhs: self.clone(),
419                operator: NumericBinaryOperator::Multiply,
420                rhs: other.clone(),
421            }
422            .into()),
423        }
424    }
425
426    pub fn divide(&self, other: &Value) -> Result<Value> {
427        use Value::*;
428
429        if other.is_zero() {
430            return Err(ValueError::DivisorShouldNotBeZero.into());
431        }
432
433        match (self, other) {
434            (I8(a), _) => a.try_divide(other),
435            (I16(a), _) => a.try_divide(other),
436            (I32(a), _) => a.try_divide(other),
437            (I64(a), _) => a.try_divide(other),
438            (I128(a), _) => a.try_divide(other),
439            (U8(a), _) => a.try_divide(other),
440            (U16(a), _) => a.try_divide(other),
441            (U32(a), _) => a.try_divide(other),
442            (U64(a), _) => a.try_divide(other),
443            (U128(a), _) => a.try_divide(other),
444            (F32(a), _) => a.try_divide(other),
445            (F64(a), _) => a.try_divide(other),
446            (Decimal(a), _) => a.try_divide(other),
447            (Interval(a), I8(b)) => Ok(Interval(*a / *b)),
448            (Interval(a), I16(b)) => Ok(Interval(*a / *b)),
449            (Interval(a), I32(b)) => Ok(Interval(*a / *b)),
450            (Interval(a), I64(b)) => Ok(Interval(*a / *b)),
451            (Interval(a), I128(b)) => Ok(Interval(*a / *b)),
452            (Interval(a), U8(b)) => Ok(Interval(*a / *b)),
453            (Interval(a), U16(b)) => Ok(Interval(*a / *b)),
454            (Interval(a), U32(b)) => Ok(Interval(*a / *b)),
455            (Interval(a), U64(b)) => Ok(Interval(*a / *b)),
456            (Interval(a), U128(b)) => Ok(Interval(*a / *b)),
457            (Interval(a), F32(b)) => Ok(Interval(*a / *b)),
458            (Interval(a), F64(b)) => Ok(Interval(*a / *b)),
459            (
460                Null,
461                I8(_) | I16(_) | I32(_) | I64(_) | I128(_) | U8(_) | U16(_) | U32(_) | U64(_)
462                | U128(_) | F32(_) | F64(_) | Decimal(_) | Null,
463            )
464            | (Interval(_), Null) => Ok(Null),
465            _ => Err(ValueError::NonNumericMathOperation {
466                lhs: self.clone(),
467                operator: NumericBinaryOperator::Divide,
468                rhs: other.clone(),
469            }
470            .into()),
471        }
472    }
473
474    pub fn bitwise_and(&self, other: &Value) -> Result<Value> {
475        use Value::*;
476
477        match (self, other) {
478            (I8(a), I8(b)) => Ok(I8(a & b)),
479            (I16(a), I16(b)) => Ok(I16(a & b)),
480            (I32(a), I32(b)) => Ok(I32(a & b)),
481            (I64(a), I64(b)) => Ok(I64(a & b)),
482            (I128(a), I128(b)) => Ok(I128(a & b)),
483            (U8(a), U8(b)) => Ok(U8(a & b)),
484            (U16(a), U16(b)) => Ok(U16(a & b)),
485            (U32(a), U32(b)) => Ok(U32(a & b)),
486            (U64(a), U64(b)) => Ok(U64(a & b)),
487            (U128(a), U128(b)) => Ok(U128(a & b)),
488            (
489                Null,
490                I8(_) | I16(_) | I32(_) | I64(_) | I128(_) | U8(_) | U16(_) | U32(_) | U64(_)
491                | U128(_) | Null,
492            )
493            | (
494                I8(_) | I16(_) | I32(_) | I64(_) | I128(_) | U8(_) | U16(_) | U32(_) | U64(_)
495                | U128(_),
496                Null,
497            ) => Ok(Null),
498            _ => Err(ValueError::NonNumericMathOperation {
499                lhs: self.clone(),
500                rhs: other.clone(),
501                operator: NumericBinaryOperator::BitwiseAnd,
502            }
503            .into()),
504        }
505    }
506
507    pub fn modulo(&self, other: &Value) -> Result<Value> {
508        use Value::*;
509
510        if other.is_zero() {
511            return Err(ValueError::DivisorShouldNotBeZero.into());
512        }
513
514        match (self, other) {
515            (I8(a), _) => a.try_modulo(other),
516            (I16(a), _) => a.try_modulo(other),
517            (I32(a), _) => a.try_modulo(other),
518            (I64(a), _) => a.try_modulo(other),
519            (I128(a), _) => a.try_modulo(other),
520            (U8(a), _) => a.try_modulo(other),
521            (U16(a), _) => a.try_modulo(other),
522            (U32(a), _) => a.try_modulo(other),
523            (U64(a), _) => a.try_modulo(other),
524            (U128(a), _) => a.try_modulo(other),
525            (F32(a), _) => a.try_modulo(other),
526            (F64(a), _) => a.try_modulo(other),
527            (Decimal(a), _) => a.try_modulo(other),
528            (
529                Null,
530                I8(_) | I16(_) | I32(_) | I64(_) | I128(_) | U8(_) | U16(_) | U32(_) | U64(_)
531                | U128(_) | F32(_) | F64(_) | Decimal(_) | Null,
532            ) => Ok(Null),
533            _ => Err(ValueError::NonNumericMathOperation {
534                lhs: self.clone(),
535                operator: NumericBinaryOperator::Modulo,
536                rhs: other.clone(),
537            }
538            .into()),
539        }
540    }
541
542    pub fn bitwise_shift_left(&self, rhs: &Value) -> Result<Value> {
543        use Value::*;
544
545        if *rhs == Null {
546            return Ok(Null);
547        }
548        let rhs = u32::try_from(rhs)?;
549        match self {
550            I8(lhs) => lhs.checked_shl(rhs).map(I8),
551            I16(lhs) => lhs.checked_shl(rhs).map(I16),
552            I32(lhs) => lhs.checked_shl(rhs).map(I32),
553            I64(lhs) => lhs.checked_shl(rhs).map(I64),
554            I128(lhs) => lhs.checked_shl(rhs).map(I128),
555            U8(lhs) => lhs.checked_shl(rhs).map(U8),
556            U16(lhs) => lhs.checked_shl(rhs).map(U16),
557            U32(lhs) => lhs.checked_shl(rhs).map(U32),
558            U64(lhs) => lhs.checked_shl(rhs).map(U64),
559            U128(lhs) => lhs.checked_shl(rhs).map(U128),
560            Null => Some(Null),
561            _ => {
562                return Err(ValueError::NonNumericMathOperation {
563                    lhs: self.clone(),
564                    rhs: U32(rhs),
565                    operator: NumericBinaryOperator::BitwiseShiftLeft,
566                }
567                .into());
568            }
569        }
570        .ok_or_else(|| {
571            ValueError::BinaryOperationOverflow {
572                lhs: self.clone(),
573                rhs: U32(rhs),
574                operator: NumericBinaryOperator::BitwiseShiftLeft,
575            }
576            .into()
577        })
578    }
579
580    pub fn bitwise_shift_right(&self, rhs: &Value) -> Result<Value> {
581        use Value::*;
582
583        if *rhs == Null {
584            return Ok(Null);
585        }
586        let rhs = u32::try_from(rhs)?;
587        match self {
588            I8(lhs) => lhs.checked_shr(rhs).map(I8),
589            I16(lhs) => lhs.checked_shr(rhs).map(I16),
590            I32(lhs) => lhs.checked_shr(rhs).map(I32),
591            I64(lhs) => lhs.checked_shr(rhs).map(I64),
592            I128(lhs) => lhs.checked_shr(rhs).map(I128),
593            U8(lhs) => lhs.checked_shr(rhs).map(U8),
594            U16(lhs) => lhs.checked_shr(rhs).map(U16),
595            U32(lhs) => lhs.checked_shr(rhs).map(U32),
596            U64(lhs) => lhs.checked_shr(rhs).map(U64),
597            U128(lhs) => lhs.checked_shr(rhs).map(U128),
598            Null => Some(Null),
599            _ => {
600                return Err(ValueError::NonNumericMathOperation {
601                    lhs: self.clone(),
602                    rhs: U32(rhs),
603                    operator: NumericBinaryOperator::BitwiseShiftRight,
604                }
605                .into());
606            }
607        }
608        .ok_or_else(|| {
609            ValueError::BinaryOperationOverflow {
610                lhs: self.clone(),
611                rhs: U32(rhs),
612                operator: NumericBinaryOperator::BitwiseShiftRight,
613            }
614            .into()
615        })
616    }
617
618    pub fn is_null(&self) -> bool {
619        matches!(self, Value::Null)
620    }
621
622    pub fn unary_plus(&self) -> Result<Value> {
623        use Value::*;
624
625        match self {
626            I8(_) | I16(_) | I32(_) | I64(_) | I128(_) | U8(_) | U16(_) | U32(_) | U64(_)
627            | U128(_) | F32(_) | F64(_) | Interval(_) | Decimal(_) => Ok(self.clone()),
628            Null => Ok(Null),
629            _ => Err(ValueError::UnaryPlusOnNonNumeric.into()),
630        }
631    }
632
633    pub fn unary_minus(&self) -> Result<Value> {
634        use Value::*;
635
636        match self {
637            I8(a) => Ok(I8(-a)),
638            I16(a) => Ok(I16(-a)),
639            I32(a) => Ok(I32(-a)),
640            I64(a) => Ok(I64(-a)),
641            I128(a) => Ok(I128(-a)),
642            F32(a) => Ok(F32(-a)),
643            F64(a) => Ok(F64(-a)),
644            Decimal(a) => Ok(Decimal(-a)),
645            Interval(a) => Ok(Interval(a.unary_minus())),
646            Null => Ok(Null),
647            _ => Err(ValueError::UnaryMinusOnNonNumeric.into()),
648        }
649    }
650
651    pub fn unary_factorial(&self) -> Result<Value> {
652        use Value::*;
653
654        fn factorial_function(a: i128) -> Result<i128> {
655            if a.is_negative() {
656                return Err(ValueError::FactorialOnNegativeNumeric.into());
657            }
658
659            (1_i128..=a)
660                .try_fold(1_i128, i128::checked_mul)
661                .ok_or_else(|| ValueError::FactorialOverflow.into())
662        }
663
664        match self {
665            I8(a) => factorial_function(i128::from(*a)).map(I128),
666            I16(a) => factorial_function(i128::from(*a)).map(I128),
667            I32(a) => factorial_function(i128::from(*a)).map(I128),
668            I64(a) => factorial_function(i128::from(*a)).map(I128),
669            I128(a) => factorial_function(*a).map(I128),
670            U8(a) => factorial_function(i128::from(*a)).map(I128),
671            U16(a) => factorial_function(i128::from(*a)).map(I128),
672            U32(a) => factorial_function(i128::from(*a)).map(I128),
673            U64(a) => factorial_function(i128::from(*a)).map(I128),
674            U128(a) => factorial_function(*a as i128).map(I128),
675            F32(_) | F64(_) => Err(ValueError::FactorialOnNonInteger.into()),
676            Null => Ok(Null),
677            _ => Err(ValueError::FactorialOnNonNumeric.into()),
678        }
679    }
680
681    pub fn unary_bitwise_not(&self) -> Result<Value> {
682        use Value::*;
683
684        match self {
685            I8(v) => Ok(Value::I8(!v)),
686            I16(v) => Ok(Value::I16(!v)),
687            I32(v) => Ok(Value::I32(!v)),
688            I64(v) => Ok(Value::I64(!v)),
689            I128(v) => Ok(Value::I128(!v)),
690            U8(v) => Ok(Value::U8(!v)),
691            U16(v) => Ok(Value::U16(!v)),
692            U32(v) => Ok(Value::U32(!v)),
693            U64(v) => Ok(Value::U64(!v)),
694            U128(v) => Ok(Value::U128(!v)),
695            F32(_) | F64(_) => Err(ValueError::UnaryBitwiseNotOnNonInteger.into()),
696            Null => Ok(Null),
697            _ => Err(ValueError::UnaryBitwiseNotOnNonNumeric.into()),
698        }
699    }
700
701    pub fn like(&self, other: &Value, case_sensitive: bool) -> Result<Value> {
702        use Value::*;
703
704        match (self, other) {
705            (Str(a), Str(b)) => a.like(b, case_sensitive).map(Bool),
706            _ => Err(ValueError::LikeOnNonString {
707                base: self.clone(),
708                pattern: other.clone(),
709                case_sensitive,
710            }
711            .into()),
712        }
713    }
714
715    pub fn extract(&self, date_type: &DateTimeField) -> Result<Value> {
716        let value = match (self, date_type) {
717            (Value::Date(v), DateTimeField::Year) => v.year().into(),
718            (Value::Date(v), DateTimeField::Month) => v.month().into(),
719            (Value::Date(v), DateTimeField::Day) => v.day().into(),
720            (Value::Time(v), DateTimeField::Hour) => v.hour().into(),
721            (Value::Time(v), DateTimeField::Minute) => v.minute().into(),
722            (Value::Time(v), DateTimeField::Second) => v.second().into(),
723            (Value::Timestamp(v), DateTimeField::Year) => v.year().into(),
724            (Value::Timestamp(v), DateTimeField::Month) => v.month().into(),
725            (Value::Timestamp(v), DateTimeField::Day) => v.day().into(),
726            (Value::Timestamp(v), DateTimeField::Hour) => v.hour().into(),
727            (Value::Timestamp(v), DateTimeField::Minute) => v.minute().into(),
728            (Value::Timestamp(v), DateTimeField::Second) => v.second().into(),
729            (Value::Interval(v), _) => {
730                return v.extract(date_type);
731            }
732            _ => {
733                return Err(ValueError::ExtractFormatNotMatched {
734                    value: self.clone(),
735                    field: *date_type,
736                }
737                .into());
738            }
739        };
740
741        Ok(Value::I64(value))
742    }
743
744    pub fn sqrt(&self) -> Result<Value> {
745        use Value::*;
746        match self {
747            I8(_) | I16(_) | I64(_) | I128(_) | U8(_) | U16(_) | U32(_) | U64(_) | U128(_)
748            | F32(_) | F64(_) => {
749                let a: f64 = self.try_into()?;
750                Ok(Value::F64(a.sqrt()))
751            }
752            Null => Ok(Value::Null),
753            _ => Err(ValueError::SqrtOnNonNumeric(self.clone()).into()),
754        }
755    }
756
757    /// Value to Big-Endian for comparison purpose
758    pub fn to_cmp_be_bytes(&self) -> Result<Vec<u8>> {
759        self.try_into().and_then(|key: Key| key.to_cmp_be_bytes())
760    }
761
762    /// # Description
763    /// The operation method differs depending on the argument.
764    /// 1. If both arguments are String
765    ///     - Support only [`Value::Str`] variant
766    ///     - Returns the position where the first letter of the substring starts if the string contains a substring.
767    ///     - Returns [`Value::I64`] 0 if the string to be found is not found.
768    ///     - Returns minimum value [`Value::I64`] 1 when the string is found.
769    ///     - Returns [`Value::Null`] if NULL parameter found.
770    ///
771    /// 2. Other arguments
772    ///     - Not Supported Yet.
773    ///
774    /// # Examples
775    /// ```
776    /// use gluesql_core::prelude::Value;
777    ///
778    /// let str1 = Value::Str("ramen".to_owned());
779    /// let str2 = Value::Str("men".to_owned());
780    ///
781    /// assert_eq!(str1.position(&str2), Ok(Value::I64(3)));
782    /// assert_eq!(str2.position(&str1), Ok(Value::I64(0)));
783    /// assert!(Value::Null.position(&str2).unwrap().is_null());
784    /// assert!(str1.position(&Value::Null).unwrap().is_null());
785    /// ```
786    pub fn position(&self, other: &Value) -> Result<Value> {
787        use Value::*;
788
789        match (self, other) {
790            (Str(from), Str(sub)) => Ok(I64(str_position(from, sub) as i64)),
791            (Null, _) | (_, Null) => Ok(Null),
792            _ => Err(ValueError::NonStringParameterInPosition {
793                from: self.clone(),
794                sub: other.clone(),
795            }
796            .into()),
797        }
798    }
799
800    pub fn find_idx(&self, sub_val: &Value, start: &Value) -> Result<Value> {
801        let start: i64 = start.try_into()?;
802        if start <= 0 {
803            return Err(ValueError::NonPositiveIntegerOffsetInFindIdx(start.to_string()).into());
804        }
805        let from = &String::from(self);
806        let sub = &String::from(sub_val);
807        let position = str_position(&from[(start - 1) as usize..], sub) as i64;
808        let position = match position {
809            0 => 0,
810            _ => position + start - 1,
811        };
812        Ok(Value::I64(position))
813    }
814}
815
816impl PartialEq for Value {
817    fn eq(&self, other: &Self) -> bool {
818        match (self, other) {
819            (Value::Bool(a), Value::Bool(b)) => a == b,
820            (Value::I8(a), Value::I8(b)) => a == b,
821            (Value::I16(a), Value::I16(b)) => a == b,
822            (Value::I32(a), Value::I32(b)) => a == b,
823            (Value::I64(a), Value::I64(b)) => a == b,
824            (Value::I128(a), Value::I128(b)) => a == b,
825            (Value::U8(a), Value::U8(b)) => a == b,
826            (Value::U16(a), Value::U16(b)) => a == b,
827            (Value::U32(a), Value::U32(b)) => a == b,
828            (Value::U64(a), Value::U64(b)) => a == b,
829            (Value::U128(a), Value::U128(b)) | (Value::Uuid(a), Value::Uuid(b)) => a == b,
830            (Value::F32(a), Value::F32(b)) => (a.is_nan() && b.is_nan()) || a == b,
831            (Value::F64(a), Value::F64(b)) => (a.is_nan() && b.is_nan()) || a == b,
832            (Value::Decimal(a), Value::Decimal(b)) => a == b,
833            (Value::Str(a), Value::Str(b)) => a == b,
834            (Value::Bytea(a), Value::Bytea(b)) => a == b,
835            (Value::Inet(a), Value::Inet(b)) => a == b,
836            (Value::Date(a), Value::Date(b)) => a == b,
837            (Value::Timestamp(a), Value::Timestamp(b)) => a == b,
838            (Value::Time(a), Value::Time(b)) => a == b,
839            (Value::Interval(a), Value::Interval(b)) => a == b,
840            (Value::Map(a), Value::Map(b)) => a == b,
841            (Value::List(a), Value::List(b)) => a == b,
842            (Value::Point(a), Value::Point(b)) => a == b,
843            (Value::Null, Value::Null) => true,
844            _ => false,
845        }
846    }
847}
848
849impl Eq for Value {}
850
851impl Hash for Value {
852    fn hash<H: Hasher>(&self, state: &mut H) {
853        const CANONICAL_F32_NAN_BITS: u32 = 0x7fc0_0000;
854        const CANONICAL_F64_NAN_BITS: u64 = 0x7ff8_0000_0000_0000;
855        const CANONICAL_F32_ZERO_BITS: u32 = 0;
856        const CANONICAL_F64_ZERO_BITS: u64 = 0;
857
858        discriminant(self).hash(state);
859
860        match self {
861            Value::Bool(v) => v.hash(state),
862            Value::I8(v) => v.hash(state),
863            Value::I16(v) => v.hash(state),
864            Value::I32(v) => v.hash(state),
865            Value::I64(v) => v.hash(state),
866            Value::I128(v) => v.hash(state),
867            Value::U8(v) => v.hash(state),
868            Value::U16(v) => v.hash(state),
869            Value::U32(v) => v.hash(state),
870            Value::U64(v) => v.hash(state),
871            Value::U128(v) | Value::Uuid(v) => v.hash(state),
872            Value::F32(v) => {
873                if v.is_nan() {
874                    CANONICAL_F32_NAN_BITS.hash(state);
875                } else if *v == 0.0f32 {
876                    CANONICAL_F32_ZERO_BITS.hash(state);
877                } else {
878                    v.to_bits().hash(state);
879                }
880            }
881            Value::F64(v) => {
882                if v.is_nan() {
883                    CANONICAL_F64_NAN_BITS.hash(state);
884                } else if *v == 0.0f64 {
885                    CANONICAL_F64_ZERO_BITS.hash(state);
886                } else {
887                    v.to_bits().hash(state);
888                }
889            }
890            Value::Decimal(v) => v.hash(state),
891            Value::Str(v) => v.hash(state),
892            Value::Bytea(v) => v.hash(state),
893            Value::Inet(v) => v.hash(state),
894            Value::Date(v) => v.hash(state),
895            Value::Timestamp(v) => v.hash(state),
896            Value::Time(v) => v.hash(state),
897            Value::Interval(v) => v.hash(state),
898            Value::Map(map) => {
899                map.hash(state);
900            }
901            Value::List(list) => list.hash(state),
902            Value::Point(p) => p.hash(state),
903            Value::Null => {
904                // Null gets its own unique hash based on discriminant only
905                // No additional data needed since discriminant already makes it unique
906            }
907        }
908    }
909}
910
911fn str_position(from_str: &str, sub_str: &str) -> usize {
912    if from_str.is_empty() || sub_str.is_empty() {
913        return 0;
914    }
915    from_str.find(sub_str).map_or(0, |position| position + 1)
916}
917
918#[cfg(test)]
919mod tests {
920    use {
921        super::{Interval, Value::*},
922        crate::data::{NumericBinaryOperator, ValueError, point::Point, value::uuid::parse_uuid},
923        chrono::{NaiveDate, NaiveTime},
924        rust_decimal::Decimal,
925        std::{collections::HashMap, net::IpAddr, str::FromStr},
926    };
927
928    fn time(hour: u32, min: u32, sec: u32) -> NaiveTime {
929        NaiveTime::from_hms_opt(hour, min, sec).unwrap()
930    }
931
932    fn date(year: i32, month: u32, day: u32) -> NaiveDate {
933        NaiveDate::from_ymd_opt(year, month, day).unwrap()
934    }
935
936    #[allow(clippy::eq_op)]
937    #[test]
938    fn evaluate_eq() {
939        use utils::Tribool;
940        use {
941            super::Interval,
942            chrono::{NaiveDateTime, NaiveTime},
943        };
944        let decimal = |n: i32| Decimal(n.into());
945        let bytea = |v: &str| Bytea(hex::decode(v).unwrap());
946        let inet = |v: &str| Inet(IpAddr::from_str(v).unwrap());
947
948        assert_eq!(Tribool::Null, Tribool::Null); // structural equality
949        assert_eq!(Tribool::Null, Null.evaluate_eq(&Null));
950        assert_eq!(Tribool::True, Bool(true).evaluate_eq(&Bool(true)));
951        assert_eq!(Tribool::True, I8(1).evaluate_eq(&I8(1)));
952        assert_eq!(Tribool::True, I16(1).evaluate_eq(&I16(1)));
953        assert_eq!(Tribool::True, I32(1).evaluate_eq(&I32(1)));
954        assert_eq!(Tribool::True, I64(1).evaluate_eq(&I64(1)));
955        assert_eq!(Tribool::True, I128(1).evaluate_eq(&I128(1)));
956        assert_eq!(Tribool::True, U8(1).evaluate_eq(&U8(1)));
957        assert_eq!(Tribool::True, U16(1).evaluate_eq(&U16(1)));
958        assert_eq!(Tribool::True, U32(1).evaluate_eq(&U32(1)));
959        assert_eq!(Tribool::True, U64(1).evaluate_eq(&U64(1)));
960        assert_eq!(Tribool::True, U128(1).evaluate_eq(&U128(1)));
961        assert_eq!(Tribool::True, I64(1).evaluate_eq(&F64(1.0)));
962        assert_eq!(Tribool::True, F32(1.0_f32).evaluate_eq(&I64(1)));
963        assert_eq!(Tribool::True, F32(6.11_f32).evaluate_eq(&F64(6.11)));
964        assert_eq!(Tribool::True, F64(1.0).evaluate_eq(&I64(1)));
965        assert_eq!(Tribool::True, F64(6.11).evaluate_eq(&F64(6.11)));
966        assert_eq!(
967            Tribool::True,
968            Str("Glue".to_owned()).evaluate_eq(&Str("Glue".to_owned()))
969        );
970        assert_eq!(Tribool::True, bytea("1004").evaluate_eq(&bytea("1004")));
971        assert_eq!(Tribool::True, inet("::1").evaluate_eq(&inet("::1")));
972        assert_eq!(
973            Tribool::True,
974            Interval(Interval::Month(1)).evaluate_eq(&Interval(Interval::Month(1)))
975        );
976        assert_eq!(
977            Tribool::True,
978            Time(NaiveTime::from_hms_opt(12, 30, 11).unwrap())
979                .evaluate_eq(&Time(NaiveTime::from_hms_opt(12, 30, 11).unwrap()))
980        );
981        assert_eq!(Tribool::True, decimal(1).evaluate_eq(&decimal(1)));
982        assert_eq!(
983            Tribool::True,
984            Date("2020-05-01".parse().unwrap()).evaluate_eq(&Date("2020-05-01".parse().unwrap()))
985        );
986        assert_eq!(
987            Tribool::True,
988            Timestamp("2020-05-01T00:00:00".parse::<NaiveDateTime>().unwrap()).evaluate_eq(
989                &Timestamp("2020-05-01T00:00:00".parse::<NaiveDateTime>().unwrap())
990            )
991        );
992        assert_eq!(
993            Tribool::True,
994            Uuid(parse_uuid("936DA01F9ABD4d9d80C702AF85C822A8").unwrap()).evaluate_eq(&Uuid(
995                parse_uuid("936DA01F9ABD4d9d80C702AF85C822A8").unwrap()
996            ))
997        );
998        assert_eq!(
999            Tribool::True,
1000            Point(Point::new(1.0, 2.0)).evaluate_eq(&Point(Point::new(1.0, 2.0)))
1001        );
1002
1003        let date = Date("2020-05-01".parse().unwrap());
1004        let timestamp = Timestamp("2020-05-01T00:00:00".parse::<NaiveDateTime>().unwrap());
1005
1006        assert_eq!(Tribool::True, date.evaluate_eq(&timestamp));
1007        assert_eq!(Tribool::True, timestamp.evaluate_eq(&date));
1008    }
1009
1010    #[test]
1011    fn cmp() {
1012        use {
1013            chrono::{NaiveDate, NaiveTime},
1014            std::cmp::Ordering,
1015        };
1016
1017        assert_eq!(
1018            Bool(true).evaluate_cmp(&Bool(false)),
1019            Some(Ordering::Greater)
1020        );
1021        assert_eq!(Bool(true).evaluate_cmp(&Bool(true)), Some(Ordering::Equal));
1022        assert_eq!(
1023            Bool(false).evaluate_cmp(&Bool(false)),
1024            Some(Ordering::Equal)
1025        );
1026        assert_eq!(Bool(false).evaluate_cmp(&Bool(true)), Some(Ordering::Less));
1027
1028        let date = Date(NaiveDate::from_ymd_opt(2020, 5, 1).unwrap());
1029        let timestamp = Timestamp(
1030            NaiveDate::from_ymd_opt(2020, 3, 1)
1031                .unwrap()
1032                .and_hms_opt(0, 0, 0)
1033                .unwrap(),
1034        );
1035
1036        assert_eq!(date.evaluate_cmp(&timestamp), Some(Ordering::Greater));
1037        assert_eq!(timestamp.evaluate_cmp(&date), Some(Ordering::Less));
1038
1039        assert_eq!(
1040            Time(NaiveTime::from_hms_opt(23, 0, 1).unwrap())
1041                .evaluate_cmp(&Time(NaiveTime::from_hms_opt(10, 59, 59).unwrap())),
1042            Some(Ordering::Greater)
1043        );
1044        assert_eq!(
1045            Interval(Interval::Month(1)).evaluate_cmp(&Interval(Interval::Month(2))),
1046            Some(Ordering::Less)
1047        );
1048
1049        let one = Decimal(rust_decimal::Decimal::ONE);
1050        let two = Decimal(rust_decimal::Decimal::TWO);
1051        assert_eq!(one.evaluate_cmp(&two), Some(Ordering::Less));
1052        assert_eq!(two.evaluate_cmp(&one), Some(Ordering::Greater));
1053
1054        assert_eq!(
1055            F32(1.0_f32).evaluate_cmp(&F32(1.0_f32)),
1056            Some(Ordering::Equal)
1057        );
1058        assert_eq!(F64(1.0).evaluate_cmp(&F64(1.0)), Some(Ordering::Equal));
1059
1060        assert_eq!(
1061            Interval(Interval::Month(1)).evaluate_cmp(&Interval(Interval::Month(1))),
1062            Some(Ordering::Equal)
1063        );
1064
1065        assert_eq!(
1066            Uuid(parse_uuid("936DA01F9ABD4d9d80C702AF85C822A8").unwrap()).evaluate_cmp(&Uuid(
1067                parse_uuid("936DA01F9ABD4d9d80C702AF85C822A8").unwrap()
1068            )),
1069            Some(Ordering::Equal)
1070        );
1071
1072        assert_eq!(Null.evaluate_cmp(&Null), None);
1073
1074        let bytea = |v: &str| Bytea(hex::decode(v).unwrap());
1075        assert_eq!(bytea("12").evaluate_cmp(&bytea("20")), Some(Ordering::Less));
1076        assert_eq!(
1077            bytea("9123").evaluate_cmp(&bytea("9122")),
1078            Some(Ordering::Greater)
1079        );
1080        assert_eq!(
1081            bytea("10").evaluate_cmp(&bytea("10")),
1082            Some(Ordering::Equal)
1083        );
1084
1085        let inet = |v: &str| Inet(IpAddr::from_str(v).unwrap());
1086        assert_eq!(
1087            inet("0.0.0.0").evaluate_cmp(&inet("127.0.0.1")),
1088            Some(Ordering::Less)
1089        );
1090        assert_eq!(
1091            inet("192.168.0.1").evaluate_cmp(&inet("127.0.0.1")),
1092            Some(Ordering::Greater)
1093        );
1094        assert_eq!(
1095            inet("::1").evaluate_cmp(&inet("::1")),
1096            Some(Ordering::Equal)
1097        );
1098    }
1099
1100    #[test]
1101    fn cmp_ints() {
1102        use std::cmp::Ordering;
1103
1104        assert_eq!(I8(0).evaluate_cmp(&I8(-1)), Some(Ordering::Greater));
1105        assert_eq!(I8(0).evaluate_cmp(&I8(0)), Some(Ordering::Equal));
1106        assert_eq!(I8(0).evaluate_cmp(&I8(1)), Some(Ordering::Less));
1107
1108        assert_eq!(I16(0).evaluate_cmp(&I8(-1)), Some(Ordering::Greater));
1109        assert_eq!(I16(0).evaluate_cmp(&I8(0)), Some(Ordering::Equal));
1110        assert_eq!(I16(0).evaluate_cmp(&I8(1)), Some(Ordering::Less));
1111
1112        assert_eq!(I32(0).evaluate_cmp(&I8(-1)), Some(Ordering::Greater));
1113        assert_eq!(I32(0).evaluate_cmp(&I8(0)), Some(Ordering::Equal));
1114        assert_eq!(I32(0).evaluate_cmp(&I8(1)), Some(Ordering::Less));
1115
1116        assert_eq!(I64(0).evaluate_cmp(&I8(-1)), Some(Ordering::Greater));
1117        assert_eq!(I64(0).evaluate_cmp(&I8(0)), Some(Ordering::Equal));
1118        assert_eq!(I64(0).evaluate_cmp(&I8(1)), Some(Ordering::Less));
1119
1120        assert_eq!(I128(0).evaluate_cmp(&I8(-1)), Some(Ordering::Greater));
1121        assert_eq!(I128(0).evaluate_cmp(&I8(0)), Some(Ordering::Equal));
1122        assert_eq!(I128(0).evaluate_cmp(&I8(1)), Some(Ordering::Less));
1123
1124        assert_eq!(U8(1).evaluate_cmp(&U8(0)), Some(Ordering::Greater));
1125        assert_eq!(U8(0).evaluate_cmp(&U8(0)), Some(Ordering::Equal));
1126        assert_eq!(U8(0).evaluate_cmp(&U8(1)), Some(Ordering::Less));
1127
1128        assert_eq!(U16(1).evaluate_cmp(&U16(0)), Some(Ordering::Greater));
1129        assert_eq!(U16(0).evaluate_cmp(&U16(0)), Some(Ordering::Equal));
1130        assert_eq!(U16(0).evaluate_cmp(&U16(1)), Some(Ordering::Less));
1131
1132        assert_eq!(U32(1).evaluate_cmp(&U32(0)), Some(Ordering::Greater));
1133        assert_eq!(U32(0).evaluate_cmp(&U32(0)), Some(Ordering::Equal));
1134        assert_eq!(U32(0).evaluate_cmp(&U32(1)), Some(Ordering::Less));
1135
1136        assert_eq!(U64(1).evaluate_cmp(&U64(0)), Some(Ordering::Greater));
1137        assert_eq!(U64(0).evaluate_cmp(&U64(0)), Some(Ordering::Equal));
1138        assert_eq!(U64(0).evaluate_cmp(&U64(1)), Some(Ordering::Less));
1139
1140        assert_eq!(U128(1).evaluate_cmp(&U128(0)), Some(Ordering::Greater));
1141        assert_eq!(U128(0).evaluate_cmp(&U128(0)), Some(Ordering::Equal));
1142        assert_eq!(U128(0).evaluate_cmp(&U128(1)), Some(Ordering::Less));
1143    }
1144
1145    #[test]
1146    fn is_zero() {
1147        for i in -1..2 {
1148            assert_eq!(I8(i).is_zero(), i == 0);
1149            assert_eq!(I16(i.into()).is_zero(), i == 0);
1150            assert_eq!(I32(i.into()).is_zero(), i == 0);
1151            assert_eq!(I64(i.into()).is_zero(), i == 0);
1152            assert_eq!(I128(i.into()).is_zero(), i == 0);
1153            assert_eq!(F32(i.into()).is_zero(), i == 0);
1154            assert_eq!(F64(i.into()).is_zero(), i == 0);
1155            assert_eq!(Decimal(i.into()).is_zero(), i == 0);
1156        }
1157        assert!(U8(0).is_zero());
1158        assert!(!U8(1).is_zero());
1159        assert!(U16(0).is_zero());
1160        assert!(!U16(1).is_zero());
1161        assert!(U32(0).is_zero());
1162        assert!(!U32(1).is_zero());
1163        assert!(U64(0).is_zero());
1164        assert!(!U64(1).is_zero());
1165        assert!(U128(0).is_zero());
1166        assert!(!U128(1).is_zero());
1167    }
1168
1169    #[test]
1170    fn arithmetic() {
1171        use chrono::{NaiveDate, NaiveTime};
1172
1173        use utils::Tribool::True;
1174        macro_rules! test {
1175            ($op: ident $a: expr, $b: expr => $c: expr) => {
1176                assert_eq!(True, $a.$op(&$b).unwrap().evaluate_eq(&$c));
1177            };
1178        }
1179
1180        macro_rules! mon {
1181            ($n: expr) => {
1182                Interval(Interval::Month($n))
1183            };
1184        }
1185
1186        let decimal = |n: i32| Decimal(n.into());
1187
1188        test!(add I8(1),    I8(2)    => I8(3));
1189        test!(add I8(1),    I16(2)    => I16(3));
1190        test!(add I8(1),    I32(2)   => I32(3));
1191        test!(add I8(1),    I64(2)   => I64(3));
1192        test!(add I8(1),    I128(2)  => I128(3));
1193        test!(add I8(1),    U8(2)    => I64(3));
1194
1195        test!(add I16(1),    I8(2)    => I16(3));
1196        test!(add I16(1),    I16(2)    => I16(3));
1197        test!(add I16(1),    I32(2)   => I32(3));
1198        test!(add I16(1),    I64(2)   => I64(3));
1199        test!(add I16(1),    I128(2)  => I128(3));
1200        test!(add I16(1),    U8(2)    => I16(3));
1201
1202        test!(add I32(1),    I8(2)      => I32(3));
1203        test!(add I32(1),    I16(2)      => I32(3));
1204        test!(add I32(1),    I32(2)     => I32(3));
1205        test!(add I32(1),    I64(2)     => I64(3));
1206        test!(add I32(1),    I128(2)    => I128(3));
1207        test!(add I32(1),    U8(2)      => I32(3));
1208
1209        test!(add I64(1),    I8(2)      => I64(3));
1210        test!(add I64(1),    I16(2)      => I64(3));
1211        test!(add I64(1),    I32(2)     => I64(3));
1212        test!(add I64(1),    I64(2)     => I64(3));
1213        test!(add I64(1),    I128(2)    => I128(3));
1214        test!(add I64(1),    U8(2)      => I64(3));
1215
1216        test!(add I128(1),    I8(2)    => I128(3));
1217        test!(add I128(1),    I16(2)    => I128(3));
1218        test!(add I128(1),    I32(2)    => I128(3));
1219        test!(add I128(1),    I64(2)   => I128(3));
1220        test!(add I128(1),    I128(2)  => I128(3));
1221        test!(add I128(1),    U8(2)    => I128(3));
1222
1223        test!(add I8(1),    F64(2.0) => F64(3.0));
1224
1225        test!(add I32(1),   I8(2)    => I32(3));
1226        test!(add I32(1),   I16(2)    => I32(3));
1227        test!(add I32(1),   I32(2)   => I32(3));
1228        test!(add I32(1),   I64(2)   => I64(3));
1229        test!(add I32(1),   F32(2.0_f32) => F32(3.0_f32));
1230        test!(add I32(1),   F64(2.0) => F64(3.0));
1231
1232        test!(add I64(1),   I8(2)    => I64(3));
1233        test!(add I64(1),   I16(2)    => I64(3));
1234        test!(add I64(1),   I32(2)   => I64(3));
1235        test!(add I64(1),   I64(2)   => I64(3));
1236        test!(add I64(1),   F32(2.0_f32) => F32(3.0_f32));
1237        test!(add I64(1),   F64(2.0) => F64(3.0));
1238
1239        test!(add I128(1),   I8(2)    => I128(3));
1240        test!(add I128(1),   I16(2)    => I128(3));
1241        test!(add I128(1),   I32(2)   => I128(3));
1242        test!(add I128(1),   I64(2)   => I128(3));
1243        test!(add I128(1),   F32(2.0_f32) => F32(3.0_f32));
1244        test!(add I128(1),   F64(2.0) => F64(3.0));
1245
1246        test!(add U8(1),   I8(2)     => I64(3));
1247        test!(add U8(1),   I16(2)    => I16(3));
1248        test!(add U8(1),   I32(2)    => I32(3));
1249        test!(add U8(1),   I64(2)    => I64(3));
1250        test!(add U8(1),   I128(2)   => I128(3));
1251        test!(add U8(1),   U8(2)     => U8(3));
1252        test!(add U8(1),   F32(2.0_f32)  => F32(3.0_f32));
1253        test!(add U8(1),   F64(2.0)  => F64(3.0));
1254
1255        test!(add U16(1),   I8(2)     => U16(3));
1256        test!(add U16(1),   I16(2)    => U16(3));
1257        test!(add U16(1),   I32(2)    => U16(3));
1258        test!(add U16(1),   I64(2)    => U16(3));
1259        test!(add U16(1),   I128(2)   => U16(3));
1260        test!(add U16(1),   U8(2)     => U16(3));
1261        test!(add U16(1),   F32(2.0_f32)  => F32(3.0_f32));
1262        test!(add U16(1),   F64(2.0)  => F64(3.0));
1263
1264        test!(add U32(1),   I8(2)     => U32(3));
1265        test!(add U32(1),   I16(2)    => U32(3));
1266        test!(add U32(1),   I32(2)    => U32(3));
1267        test!(add U32(1),   I64(2)    => U32(3));
1268        test!(add U32(1),   I128(2)   => U32(3));
1269        test!(add U32(1),   U8(2)     => U32(3));
1270        test!(add U32(1),   U16(2)     => U32(3));
1271        test!(add U32(1),   U32(2)     => U32(3));
1272        test!(add U32(1),   F32(2.0_f32)  => F32(3.0_f32));
1273        test!(add U32(1),   F64(2.0)  => F64(3.0));
1274
1275        test!(add U64(1),   I8(2)     => U64(3));
1276        test!(add U64(1),   I16(2)    => U64(3));
1277        test!(add U64(1),   I32(2)    => U64(3));
1278        test!(add U64(1),   I64(2)    => U64(3));
1279        test!(add U64(1),   I128(2)   => U64(3));
1280        test!(add U64(1),   U8(2)     => U64(3));
1281        test!(add U64(1),   U16(2)     => U64(3));
1282        test!(add U64(1),   U32(2)     => U64(3));
1283        test!(add U64(1),   F32(2.0_f32)  => F32(3.0_f32));
1284        test!(add U64(1),   F64(2.0)  => F64(3.0));
1285
1286        test!(add U128(1),   I8(2)     => U128(3));
1287        test!(add U128(1),   I16(2)    => U128(3));
1288        test!(add U128(1),   I32(2)    => U128(3));
1289        test!(add U128(1),   I64(2)    => U128(3));
1290        test!(add U128(1),   I128(2)   => U128(3));
1291        test!(add U128(1),   U8(2)     => U128(3));
1292        test!(add U128(1),   U16(2)     => U128(3));
1293        test!(add U128(1),   U32(2)     => U128(3));
1294        test!(add U128(1),   F32(2.0_f32)  => F32(3.0_f32));
1295        test!(add U128(1),   F64(2.0)  => F64(3.0));
1296
1297        test!(add F32(1.0_f32), F32(2.0_f32) => F32(3.0_f32));
1298        test!(add F32(1.0_f32), F64(2.0) => F64(3.0));
1299        test!(add F32(1.0_f32), I8(2)    => F32(3.0_f32));
1300        test!(add F32(1.0_f32), I32(2)   => F32(3.0_f32));
1301        test!(add F32(1.0_f32), I64(2)   => F32(3.0_f32));
1302        test!(add F32(1.0_f32), U8(2)   => F32(3.0_f32));
1303        test!(add F32(1.0_f32), U16(2)   => F32(3.0_f32));
1304        test!(add F32(1.0_f32), U32(2)   => F32(3.0_f32));
1305        test!(add F32(1.0_f32), U64(2)   => F32(3.0_f32));
1306        test!(add F32(1.0_f32), U128(2)   => F32(3.0_f32));
1307
1308        test!(add F64(1.0), F64(2.0) => F64(3.0));
1309        test!(add F64(1.0), F32(2.0_f32) => F32(3.0_f32));
1310        test!(add F64(1.0), I8(2)    => F64(3.0));
1311        test!(add F64(1.0), I32(2)   => F64(3.0));
1312        test!(add F64(1.0), I64(2)   => F64(3.0));
1313        test!(add F64(1.0), U8(2)    => F64(3.0));
1314
1315        test!(add decimal(1), decimal(2) => decimal(3));
1316
1317        test!(add
1318            Date(date(2021, 11, 11)),
1319            mon!(14)
1320            =>
1321            Timestamp(date(2023, 1, 11).and_hms_opt(0, 0, 0).unwrap())
1322        );
1323        test!(add
1324            Date(date(2021, 5, 7)),
1325            Time(time(12, 0, 0))
1326            =>
1327            Timestamp(date(2021, 5, 7).and_hms_opt(12, 0, 0).unwrap())
1328        );
1329        test!(add
1330            Timestamp(date(2021, 11, 11).and_hms_opt(0, 0, 0).unwrap()),
1331            mon!(14)
1332            =>
1333            Timestamp(date(2023, 1, 11).and_hms_opt(0, 0, 0).unwrap())
1334        );
1335        test!(add
1336            Time(time(1, 4, 6)),
1337            Interval(Interval::hours(20))
1338            =>
1339            Time(time(21, 4, 6))
1340        );
1341        test!(add
1342            Time(time(23, 10, 0)),
1343            Interval(Interval::hours(5))
1344            =>
1345            Time(time(4, 10, 0))
1346        );
1347        test!(add mon!(1),    mon!(2)    => mon!(3));
1348
1349        test!(subtract I8(3),    I8(2)    => I8(1));
1350        test!(subtract I8(3),    I16(2)    => I8(1));
1351        test!(subtract I8(3),    I32(2)   => I32(1));
1352        test!(subtract I8(3),    I64(2)   => I64(1));
1353        test!(subtract I8(3),    I128(2)  => I128(1));
1354        test!(subtract I8(3),    U8(2)  => I64(1));
1355
1356        test!(subtract I32(3),    I8(2)    => I32(1));
1357        test!(subtract I32(3),    I16(2)    => I32(1));
1358        test!(subtract I32(3),    I32(2)   => I32(1));
1359        test!(subtract I32(3),    I64(2)   => I64(1));
1360        test!(subtract I32(3),    I128(2)  => I128(1));
1361        test!(subtract I32(3),    U8(2)  => I32(1));
1362
1363        test!(subtract I64(3),    I8(2)    => I64(1));
1364        test!(subtract I64(3),    I16(2)    => I64(1));
1365        test!(subtract I64(3),    I32(2)   => I64(1));
1366        test!(subtract I64(3),    I64(2)   => I64(1));
1367        test!(subtract I64(3),    I128(2)  => I128(1));
1368        test!(subtract I64(3),    U8(2)    => I64(1));
1369
1370        test!(subtract I128(3),    I8(2)   => I128(1));
1371        test!(subtract I128(3),    I16(2)   => I128(1));
1372        test!(subtract I128(3),    I32(2)  => I128(1));
1373        test!(subtract I128(3),    I64(2)  => I128(1));
1374        test!(subtract I128(3),    I128(2) => I128(1));
1375        test!(subtract I128(3),    U8(2)   => I128(1));
1376
1377        test!(subtract U8(3),   I8(2)     => I64(1));
1378        test!(subtract U8(3),   I16(2)    => I16(1));
1379        test!(subtract U8(3),   I32(2)    => I32(1));
1380        test!(subtract U8(3),   I64(2)    => I64(1));
1381        test!(subtract U8(3),   I128(2)   => I128(1));
1382        test!(subtract U8(3),   U8(2)     => U8(1));
1383        test!(subtract U8(3),   F32(2.0_f32)  => F32(1.0_f32));
1384        test!(subtract U8(3),   F64(2.0)  => F64(1.0));
1385
1386        test!(subtract U16(3),   I8(2)     => U16(1));
1387        test!(subtract U16(3),   I16(2)    => U16(1));
1388        test!(subtract U16(3),   I32(2)    => U16(1));
1389        test!(subtract U16(3),   I64(2)    => U16(1));
1390        test!(subtract U16(3),   I128(2)   => U16(1));
1391        test!(subtract U16(3),   U8(2)     => U16(1));
1392        test!(subtract U16(3),   F32(2.0_f32)  => F32(1.0_f32));
1393        test!(subtract U16(3),   F64(2.0)  => F64(1.0));
1394
1395        test!(subtract U32(3),   I8(2)     => U32(1));
1396        test!(subtract U32(3),   I16(2)    => U32(1));
1397        test!(subtract U32(3),   I32(2)    => U32(1));
1398        test!(subtract U32(3),   I64(2)    => U32(1));
1399        test!(subtract U32(3),   I128(2)   => U32(1));
1400        test!(subtract U32(3),   U8(2)     => U32(1));
1401        test!(subtract U32(3),   F32(2.0_f32)  => F32(1.0_f32));
1402        test!(subtract U32(3),   F64(2.0)  => F64(1.0));
1403
1404        test!(subtract U64(3),   I8(2)     => U64(1));
1405        test!(subtract U64(3),   I16(2)    => U64(1));
1406        test!(subtract U64(3),   I32(2)    => U64(1));
1407        test!(subtract U64(3),   I64(2)    => U64(1));
1408        test!(subtract U64(3),   I128(2)   => U64(1));
1409        test!(subtract U64(3),   U8(2)     => U64(1));
1410        test!(subtract U64(3),   F32(2.0_f32)  => F32(1.0_f32));
1411        test!(subtract U64(3),   F64(2.0)  => F64(1.0));
1412
1413        test!(subtract U128(3),   I8(2)     => U128(1));
1414        test!(subtract U128(3),   I16(2)    => U128(1));
1415        test!(subtract U128(3),   I32(2)    => U128(1));
1416        test!(subtract U128(3),   I64(2)    => U128(1));
1417        test!(subtract U128(3),   I128(2)   => U128(1));
1418        test!(subtract U128(3),   U8(2)     => U128(1));
1419        test!(subtract U128(3),   F32(2.0_f32)  => F32(1.0_f32));
1420        test!(subtract U128(3),   F64(2.0)  => F64(1.0));
1421
1422        test!(subtract I8(3),    F32(2.0_f32) => F32(1.0_f32));
1423        test!(subtract I32(3),   F32(2.0_f32) => F32(1.0_f32));
1424        test!(subtract I64(3),   F32(2.0_f32) => F32(1.0_f32));
1425        test!(subtract I128(3),  F32(2.0_f32) => F32(1.0_f32));
1426        test!(subtract U8(3),    F32(2.0_f32) => F32(1.0_f32));
1427        test!(subtract U32(3),   F32(2.0_f32) => F32(1.0_f32));
1428        test!(subtract U64(3),   F32(2.0_f32) => F32(1.0_f32));
1429        test!(subtract U128(3),  F32(2.0_f32) => F32(1.0_f32));
1430
1431        test!(subtract I8(3),    F64(2.0) => F64(1.0));
1432        test!(subtract I32(3),   F64(2.0) => F64(1.0));
1433        test!(subtract I64(3),   F64(2.0) => F64(1.0));
1434        test!(subtract I128(3),  F64(2.0) => F64(1.0));
1435
1436        test!(subtract I32(3),   I8(2)    => I64(1));
1437        test!(subtract I32(3),   I16(2)    => I64(1));
1438        test!(subtract I32(3),   I32(2)   => I32(1));
1439        test!(subtract I32(3),   I64(2)   => I64(1));
1440        test!(subtract I32(3),   I128(2)  => I128(1));
1441
1442        test!(subtract I32(3),   F32(2.0_f32) => F32(1.0_f32));
1443        test!(subtract I32(3),   F64(2.0) => F64(1.0));
1444
1445        test!(subtract I64(3),   I8(2)    => I64(1));
1446        test!(subtract I64(3),   I16(2)    => I64(1));
1447        test!(subtract I64(3),   I32(2)   => I64(1));
1448        test!(subtract I64(3),   I64(2)   => I64(1));
1449        test!(subtract I64(3),   I128(2)   => I64(1));
1450        test!(subtract I64(3),   F32(2.0_f32) => F32(1.0_f32));
1451        test!(subtract I64(3),   F64(2.0) => F64(1.0));
1452
1453        test!(subtract F32(3.0_f32), F32(2.0_f32) => F32(1.0_f32));
1454        test!(subtract F32(3.0_f32), F64(2.0) => F64(1.0));
1455        test!(subtract F32(3.0_f32), I8(2)    => F32(1.0_f32));
1456        test!(subtract F32(3.0_f32), I64(2)   => F32(1.0_f32));
1457
1458        test!(subtract F64(3.0), F32(2.0_f32) => F32(1.0_f32));
1459        test!(subtract F64(3.0), F64(2.0) => F64(1.0));
1460        test!(subtract F64(3.0), I8(2)    => F64(1.0));
1461        test!(subtract F64(3.0), I64(2)   => F64(1.0));
1462        test!(subtract F64(3.0), U8(2)   => F64(1.0));
1463
1464        test!(subtract decimal(3), decimal(2) => decimal(1));
1465
1466        test!(subtract
1467            Date(NaiveDate::from_ymd_opt(2021, 11, 11).unwrap()),
1468            Date(NaiveDate::from_ymd_opt(2021, 6, 11).unwrap())
1469            =>
1470            Interval(Interval::days(153))
1471        );
1472        test!(subtract
1473            Date(NaiveDate::from_ymd_opt(2021, 1, 1).unwrap()),
1474            Interval(Interval::days(365))
1475            =>
1476            Timestamp(NaiveDate::from_ymd_opt(2020, 1, 2).unwrap().and_hms_opt(0, 0, 0).unwrap())
1477        );
1478        test!(subtract
1479            Timestamp(NaiveDate::from_ymd_opt(2021, 1, 1).unwrap().and_hms_opt(15, 0, 0).unwrap()),
1480            Timestamp(NaiveDate::from_ymd_opt(2021, 1, 1).unwrap().and_hms_opt(12, 0, 0).unwrap())
1481            =>
1482            Interval(Interval::hours(3))
1483        );
1484        test!(subtract
1485            Timestamp(NaiveDate::from_ymd_opt(2021, 1, 1).unwrap().and_hms_opt(0, 3, 0).unwrap()),
1486            Interval(Interval::days(365))
1487            =>
1488            Timestamp(NaiveDate::from_ymd_opt(2020, 1, 2).unwrap().and_hms_opt(0, 3, 0).unwrap())
1489        );
1490        test!(subtract
1491            Time(time(1, 4, 6)),
1492            Interval(Interval::hours(20))
1493            =>
1494            Time(time(5, 4, 6))
1495        );
1496        test!(subtract
1497            Time(time(23, 10, 0)),
1498            Interval(Interval::hours(5))
1499            =>
1500            Time(time(18, 10, 0))
1501        );
1502        test!(subtract mon!(1),  mon!(2)  => mon!(-1));
1503
1504        test!(multiply I8(3),    I8(2)    => I8(6));
1505        test!(multiply I8(3),    I16(2)    => I8(6));
1506        test!(multiply I8(3),    I32(2)    => I32(6));
1507        test!(multiply I8(3),    I64(2)   => I64(6));
1508        test!(multiply I8(3),    I128(2)  => I128(6));
1509        test!(multiply I8(3),    U8(2)    => I64(6));
1510
1511        test!(multiply I64(3),    I8(2)    => I64(6));
1512        test!(multiply I64(3),    I16(2)    => I64(6));
1513        test!(multiply I64(3),    I32(2)   => I64(6));
1514        test!(multiply I64(3),    I64(2)   => I64(6));
1515        test!(multiply I64(3),    I128(2)  => I128(6));
1516        test!(multiply I64(3),    U8(2)    => I64(6));
1517
1518        test!(multiply I128(3),    I8(2)    => I128(6));
1519        test!(multiply I128(3),    I16(2)    => I128(6));
1520        test!(multiply I128(3),    I32(2)    => I128(6));
1521        test!(multiply I128(3),    I64(2)   => I128(6));
1522        test!(multiply I128(3),    I128(2)  => I128(6));
1523        test!(multiply I128(3),    U8(2)  => I128(6));
1524
1525        test!(multiply I8(3),    F32(2.0_f32) => F32(6.0_f32));
1526        test!(multiply I16(3),    F32(2.0_f32) => F32(6.0_f32));
1527        test!(multiply I32(3),    F32(2.0_f32) => F32(6.0_f32));
1528        test!(multiply I64(3),   F32(2.0_f32) => F32(6.0_f32));
1529        test!(multiply I128(3),    F32(2.0_f32) => F32(6.0_f32));
1530        test!(multiply I128(3),    U8(2) => I128(6));
1531
1532        test!(multiply I8(3),    F64(2.0) => F64(6.0));
1533        test!(multiply I16(3),    F64(2.0) => F64(6.0));
1534        test!(multiply I32(3),    F64(2.0) => F64(6.0));
1535        test!(multiply I64(3),   F64(2.0) => F64(6.0));
1536        test!(multiply I128(3),    F64(2.0) => F64(6.0));
1537        test!(multiply I128(3),    U8(2) => I128(6));
1538
1539        test!(multiply U8(3),   I8(2)     => I64(6));
1540        test!(multiply U8(3),   I16(2)    => I16(6));
1541        test!(multiply U8(3),   I32(2)    => I32(6));
1542        test!(multiply U8(3),   I64(2)    => I64(6));
1543        test!(multiply U8(3),   I128(2)   => I128(6));
1544        test!(multiply U8(3),   U8(2)     => U8(6));
1545        test!(multiply U8(3),   F32(2.0_f32)  => F32(6.0_f32));
1546        test!(multiply U8(3),   F64(2.0)  => F64(6.0));
1547
1548        test!(multiply U16(3),   I8(2)     => U16(6));
1549        test!(multiply U16(3),   I16(2)    => U16(6));
1550        test!(multiply U16(3),   I32(2)    => U16(6));
1551        test!(multiply U16(3),   I64(2)    => U16(6));
1552        test!(multiply U16(3),   I128(2)   => U16(6));
1553        test!(multiply U16(3),   U8(2)     => U16(6));
1554        test!(multiply U16(3),   F32(2.0_f32)  => F64(6.0));
1555        test!(multiply U16(3),   F64(2.0)  => F64(6.0));
1556
1557        test!(multiply U32(3),   I8(2)     => U32(6));
1558        test!(multiply U32(3),   I16(2)    => U32(6));
1559        test!(multiply U32(3),   I32(2)    => U32(6));
1560        test!(multiply U32(3),   I64(2)    => U32(6));
1561        test!(multiply U32(3),   I128(2)   => U32(6));
1562        test!(multiply U32(3),   U8(2)     => U32(6));
1563        test!(multiply U32(3),   F32(2.0_f32)  => F64(6.0));
1564        test!(multiply U32(3),   F64(2.0)  => F64(6.0));
1565
1566        test!(multiply U64(3),   I8(2)     => U64(6));
1567        test!(multiply U64(3),   I16(2)    => U64(6));
1568        test!(multiply U64(3),   I32(2)    => U64(6));
1569        test!(multiply U64(3),   I64(2)    => U64(6));
1570        test!(multiply U64(3),   I128(2)   => U64(6));
1571        test!(multiply U64(3),   U8(2)     => U64(6));
1572        test!(multiply U64(3),   F32(2.0_f32)  => F64(6.0));
1573        test!(multiply U64(3),   F64(2.0)  => F64(6.0));
1574
1575        test!(multiply U128(3),   I8(2)     => U128(6));
1576        test!(multiply U128(3),   I16(2)    => U128(6));
1577        test!(multiply U128(3),   I32(2)    => U128(6));
1578        test!(multiply U128(3),   I64(2)    => U128(6));
1579        test!(multiply U128(3),   I128(2)   => U128(6));
1580        test!(multiply U128(3),   U8(2)     => U128(6));
1581        test!(multiply U128(3),   F32(2.0_f32)  => F32(6.0_f32));
1582        test!(multiply U128(3),   F64(2.0)  => F64(6.0));
1583
1584        test!(multiply F32(3.0_f32), F32(2.0_f32) => F32(6.0_f32));
1585        test!(multiply F32(3.0_f32), F64(2.0) => F64(6.0));
1586        test!(multiply F32(3.0_f32), I8(2)    => F32(6.0_f32));
1587        test!(multiply F32(3.0_f32), I32(2)   => F32(6.0_f32));
1588        test!(multiply F32(3.0_f32), I64(2)   => F32(6.0_f32));
1589        test!(multiply F32(3.0_f32), I128(2)  => F32(6.0_f32));
1590        test!(multiply F32(3.0_f32), U8(2)    => F32(6.0_f32));
1591
1592        test!(multiply F64(3.0), F64(2.0) => F64(6.0));
1593        test!(multiply F64(3.0), F32(2.0_f32) => F32(6.0_f32));
1594        test!(multiply F64(3.0), I8(2)    => F64(6.0));
1595        test!(multiply F64(3.0), I32(2)   => F64(6.0));
1596        test!(multiply F64(3.0), I64(2)   => F64(6.0));
1597        test!(multiply F64(3.0), I128(2)  => F64(6.0));
1598        test!(multiply F64(3.0), U8(2)    => F64(6.0));
1599
1600        test!(multiply decimal(3), decimal(2) => decimal(6));
1601
1602        test!(multiply I8(3),    mon!(3)  => mon!(9));
1603        test!(multiply I16(3),   mon!(3)  => mon!(9));
1604        test!(multiply I32(3),   mon!(3)  => mon!(9));
1605        test!(multiply I64(3),   mon!(3)  => mon!(9));
1606        test!(multiply I128(3),  mon!(3)  => mon!(9));
1607        test!(multiply F32(3.0_f32), mon!(3)  => mon!(9));
1608        test!(multiply F64(3.0), mon!(3)  => mon!(9));
1609        test!(multiply mon!(3),  I8(2)    => mon!(6));
1610        test!(multiply mon!(3),  I16(2)   => mon!(6));
1611        test!(multiply mon!(3),  I32(2)   => mon!(6));
1612        test!(multiply mon!(3),  I64(2)   => mon!(6));
1613        test!(multiply mon!(3),  I128(2)  => mon!(6));
1614        test!(multiply mon!(3),  F32(2.0_f32) => mon!(6));
1615        test!(multiply mon!(3),  F32(2.0_f32) => mon!(6));
1616        test!(multiply mon!(3),  F64(2.0) => mon!(6));
1617
1618        test!(divide I8(0),     I8(5)   => I8(0));
1619        test!(divide I8(0),     I16(5)   => I8(0));
1620        test!(divide I8(0),     I32(5)  => I32(0));
1621        test!(divide I8(0),     I64(5)  => I64(0));
1622        test!(divide I8(0),     I128(5) => I128(0));
1623        test!(divide I8(0),     U8(5)   => I64(0));
1624        assert_eq!(
1625            I8(5).divide(&I8(0)),
1626            Err(ValueError::DivisorShouldNotBeZero.into())
1627        );
1628
1629        test!(divide I8(6),    I8(2)    => I8(3));
1630        test!(divide I8(6),    I16(2)    => I8(3));
1631        test!(divide I8(6),    I32(2)    => I8(3));
1632        test!(divide I8(6),    I64(2)   => I64(3));
1633        test!(divide I8(6),    I128(2)  => I128(3));
1634        test!(divide I8(6),    U8(2)    => I64(3));
1635
1636        test!(divide I64(6),    I8(2)    => I64(3));
1637        test!(divide I64(6),    I16(2)    => I64(3));
1638        test!(divide I64(6),    I32(2)    => I64(3));
1639        test!(divide I64(6),    I64(2)   => I64(3));
1640        test!(divide I64(6),    I128(2)  => I128(3));
1641        test!(divide I64(6),    U8(2)  => I64(3));
1642
1643        test!(divide I128(6),    I8(2)    => I128(3));
1644        test!(divide I128(6),    I16(2)    => I128(3));
1645        test!(divide I128(6),    I32(2)    => I128(3));
1646        test!(divide I128(6),    I64(2)   => I128(3));
1647        test!(divide I128(6),    I128(2)  => I128(3));
1648        test!(divide I128(6),    U8(2)  => I64(3));
1649
1650        test!(divide I128(6),    I8(2)    => I128(3));
1651        test!(divide I128(6),    I16(2)    => I128(3));
1652        test!(divide I128(6),    I32(2)    => I128(3));
1653        test!(divide I128(6),    I64(2)   => I128(3));
1654        test!(divide I128(6),    I128(2)  => I128(3));
1655
1656        test!(divide U8(6),   I8(2)     => I64(3));
1657        test!(divide U8(6),   I16(2)    => I16(3));
1658        test!(divide U8(6),   I32(2)    => I32(3));
1659        test!(divide U8(6),   I64(2)    => I64(3));
1660        test!(divide U8(6),   I128(2)   => I128(3));
1661        test!(divide U8(6),   U8(2)     => U8(3));
1662        test!(divide U8(6),   F32(2.0_f32)  => F64(3.0));
1663        test!(divide U8(6),   F64(2.0)  => F64(3.0));
1664
1665        test!(divide U16(6),   I8(2)     => U16(3));
1666        test!(divide U16(6),   I16(2)    => U16(3));
1667        test!(divide U16(6),   I32(2)    => U16(3));
1668        test!(divide U16(6),   I64(2)    => U16(3));
1669        test!(divide U16(6),   I128(2)   => U16(3));
1670        test!(divide U16(6),   U8(2)     => U16(3));
1671        test!(divide U16(6),   F32(2.0_f32)  => F64(3.0));
1672        test!(divide U16(6),   F64(2.0)  => F64(3.0));
1673
1674        test!(divide U32(6),   I8(2)     => U32(3));
1675        test!(divide U32(6),   I16(2)    => U32(3));
1676        test!(divide U32(6),   I32(2)    => U32(3));
1677        test!(divide U32(6),   I64(2)    => U32(3));
1678        test!(divide U32(6),   I128(2)   => U32(3));
1679        test!(divide U32(6),   U8(2)     => U32(3));
1680        test!(divide U32(6),   F32(2.0_f32)  => F64(3.0));
1681        test!(divide U32(6),   F64(2.0)  => F64(3.0));
1682
1683        test!(divide U64(6),   I8(2)     => U64(3));
1684        test!(divide U64(6),   I16(2)    => U64(3));
1685        test!(divide U64(6),   I32(2)    => U64(3));
1686        test!(divide U64(6),   I64(2)    => U64(3));
1687        test!(divide U64(6),   I128(2)   => U64(3));
1688        test!(divide U64(6),   U8(2)     => U64(3));
1689        test!(divide U64(6),   F32(2.0_f32)  => F64(3.0));
1690        test!(divide U64(6),   F64(2.0)  => F64(3.0));
1691
1692        test!(divide U128(6),   I8(2)     => U128(3));
1693        test!(divide U128(6),   I16(2)    => U128(3));
1694        test!(divide U128(6),   I32(2)    => U128(3));
1695        test!(divide U128(6),   I64(2)    => U128(3));
1696        test!(divide U128(6),   I128(2)   => U128(3));
1697        test!(divide U128(6),   U8(2)     => U128(3));
1698        test!(divide U128(6),   F64(2.0)  => F64(3.0));
1699
1700        test!(divide I8(6),    F64(2.0) => F64(3.0));
1701        test!(divide I32(6),    F64(2.0) => F64(3.0));
1702        test!(divide I64(6),   F64(2.0) => F64(3.0));
1703        test!(divide I128(6),    F64(2.0) => F64(3.0));
1704        test!(divide F32(6.0_f32),    F64(2.0) => F64(3.0));
1705
1706        test!(divide I8(6),    F32(2.0_f32) => F32(3.0_f32));
1707        test!(divide I32(6),    F32(2.0_f32) => F32(3.0_f32));
1708        test!(divide I64(6),   F32(2.0_f32) => F32(3.0_f32));
1709        test!(divide I128(6),    F32(2.0_f32) => F32(3.0_f32));
1710        test!(divide F64(6.0), F32(2.0_f32) => F32(3.0_f32));
1711
1712        test!(divide F32(6.0_f32), I8(2)    => F32(3.0_f32));
1713        test!(divide F32(6.0_f32), I16(2)    => F32(3.0_f32));
1714        test!(divide F32(6.0_f32), I32(2)    => F32(3.0_f32));
1715        test!(divide F32(6.0_f32), I64(2)   => F32(3.0_f32));
1716        test!(divide F32(6.0_f32), I128(2)    => F32(3.0_f32));
1717        test!(divide F64(6.0), F32(2.0_f32) => F32(3.0_f32));
1718
1719        test!(divide F64(6.0), I8(2)    => F64(3.0));
1720        test!(divide F64(6.0), I16(2)    => F64(3.0));
1721        test!(divide F64(6.0), I32(2)    => F64(3.0));
1722        test!(divide F64(6.0), I64(2)   => F64(3.0));
1723        test!(divide F64(6.0), I128(2)    => F64(3.0));
1724        test!(divide F64(6.0), U8(2)    => F64(3.0));
1725        test!(divide F64(6.0), F32(2.0_f32) => F32(3.0_f32));
1726
1727        test!(divide mon!(6),  I8(2)    => mon!(3));
1728        test!(divide mon!(6),  I16(2)    => mon!(3));
1729        test!(divide mon!(6),  I32(2)    => mon!(3));
1730        test!(divide mon!(6),  I64(2)   => mon!(3));
1731        test!(divide mon!(6),  I128(2)    => mon!(3));
1732        test!(divide mon!(6),  U8(2)    => mon!(3));
1733        test!(divide mon!(6),  U16(2)    => mon!(3));
1734        test!(divide mon!(6),  U32(2)    => mon!(3));
1735        test!(divide mon!(6),  U64(2)    => mon!(3));
1736        test!(divide mon!(6),  U128(2)    => mon!(3));
1737        test!(divide mon!(6),  F32(2.0_f32) => mon!(3));
1738        test!(divide mon!(6),  F64(2.0) => mon!(3));
1739
1740        test!(modulo I8(6),    I8(4)    => I8(2));
1741        test!(modulo I8(6),    I16(4)    => I8(2));
1742        test!(modulo I8(6),    I32(4)    => I8(2));
1743        test!(modulo I8(6),    I64(4)   => I64(2));
1744        test!(modulo I8(6),    I128(4)  => I128(2));
1745
1746        assert_eq!(
1747            I8(5).modulo(&I8(0)),
1748            Err(ValueError::DivisorShouldNotBeZero.into())
1749        );
1750
1751        test!(modulo I64(6),    I8(4)    => I64(2));
1752        test!(modulo I64(6),    I16(4)    => I64(2));
1753        test!(modulo I64(6),    I32(4)   => I64(2));
1754        test!(modulo I64(6),    I64(4)   => I64(2));
1755        test!(modulo I64(6),    I128(4)  => I128(2));
1756
1757        test!(modulo I128(6),    I8(4)    => I128(2));
1758        test!(modulo I128(6),    I16(4)    => I128(2));
1759        test!(modulo I128(6),    I32(4)    => I128(2));
1760        test!(modulo I128(6),    I64(4)   => I128(2));
1761        test!(modulo I128(6),    I128(4)  => I128(2));
1762
1763        test!(modulo I8(6),   I8(2)   => I8(0));
1764        test!(modulo I8(6),   F32(2.0_f32) => F32(0.0_f32));
1765        test!(modulo I8(6),   F64(2.0) => F64(0.0));
1766        test!(modulo I32(6),   I32(2)   => I32(0));
1767        test!(modulo I32(6),   F64(2.0) => F64(0.0));
1768        test!(modulo I64(6),   I32(2)   => I32(0));
1769        test!(modulo I64(6),   F64(2.0) => F64(0.0));
1770        test!(modulo F32(6.0_f32), I64(2)   => F32(0.0_f32));
1771        test!(modulo F32(6.0_f32), F32(2.0_f32) => F32(0.0_f32));
1772        test!(modulo F64(6.0), I64(2)   => F64(0.0));
1773        test!(modulo F64(6.0), F64(2.0) => F64(0.0));
1774        test!(modulo I128(6),   I8(2)   => I128(0));
1775        test!(modulo I128(6),   I16(2)   => I128(0));
1776        test!(modulo I128(6),   I32(2)   => I128(0));
1777        test!(modulo I128(6),   I64(2)   => I128(0));
1778        test!(modulo I128(6),   I128(2)   => I128(0));
1779        test!(modulo I128(6),   F64(2.0) => F64(0.0));
1780        test!(modulo I128(6),   F32(2.0_f32) => F32(0.0_f32));
1781
1782        macro_rules! null_test {
1783            ($op: ident $a: expr, $b: expr) => {
1784                assert!($a.$op(&$b).unwrap().is_null());
1785            };
1786        }
1787
1788        let date = || Date(NaiveDate::from_ymd_opt(1989, 3, 1).unwrap());
1789        let time = || Time(NaiveTime::from_hms_opt(6, 1, 1).unwrap());
1790        let ts = || {
1791            Timestamp(
1792                NaiveDate::from_ymd_opt(1989, 1, 1)
1793                    .unwrap()
1794                    .and_hms_opt(0, 0, 0)
1795                    .unwrap(),
1796            )
1797        };
1798
1799        null_test!(add      I8(1),    Null);
1800        null_test!(add      I16(1),    Null);
1801        null_test!(add      I32(1),   Null);
1802        null_test!(add      I64(1),   Null);
1803        null_test!(add      I128(1),   Null);
1804        null_test!(add      U8(1),   Null);
1805        null_test!(add      U16(1),   Null);
1806        null_test!(add      U32(1),   Null);
1807        null_test!(add      U64(1),   Null);
1808        null_test!(add      U128(1),   Null);
1809        null_test!(add      F32(1.0_f32), Null);
1810        null_test!(add      F64(1.0), Null);
1811        null_test!(add      decimal(1), Null);
1812        null_test!(add      date(),   Null);
1813        null_test!(add      ts(),     Null);
1814        null_test!(add      time(),   Null);
1815        null_test!(add      mon!(1),  Null);
1816        null_test!(subtract I8(1),    Null);
1817        null_test!(subtract I16(1),    Null);
1818        null_test!(subtract I32(1),    Null);
1819        null_test!(subtract I64(1),   Null);
1820        null_test!(subtract I128(1),   Null);
1821        null_test!(subtract U8(1),   Null);
1822        null_test!(subtract U16(1),   Null);
1823        null_test!(subtract U32(1),   Null);
1824        null_test!(subtract U64(1),   Null);
1825        null_test!(subtract U128(1),   Null);
1826        null_test!(subtract F32(1.0_f32), Null);
1827        null_test!(subtract F64(1.0), Null);
1828        null_test!(subtract decimal(1), Null);
1829        null_test!(subtract date(),   Null);
1830        null_test!(subtract ts(),     Null);
1831        null_test!(subtract time(),   Null);
1832        null_test!(subtract mon!(1),  Null);
1833        null_test!(multiply I8(1),    Null);
1834        null_test!(multiply I16(1),    Null);
1835        null_test!(multiply I32(1),   Null);
1836        null_test!(multiply I64(1),   Null);
1837        null_test!(multiply I128(1),   Null);
1838        null_test!(multiply U8(1),   Null);
1839        null_test!(multiply U16(1),   Null);
1840        null_test!(multiply U32(1),   Null);
1841        null_test!(multiply U64(1),   Null);
1842        null_test!(multiply U128(1),   Null);
1843        null_test!(multiply F32(1.0_f32), Null);
1844        null_test!(multiply F64(1.0), Null);
1845        null_test!(multiply decimal(1), Null);
1846        null_test!(multiply mon!(1),  Null);
1847        null_test!(divide   I8(1),    Null);
1848        null_test!(divide   I16(1),    Null);
1849        null_test!(divide   I32(1),    Null);
1850        null_test!(divide   I64(1),   Null);
1851        null_test!(divide   I128(1),   Null);
1852        null_test!(divide   U8(1),   Null);
1853        null_test!(divide   U16(1),   Null);
1854        null_test!(divide   U32(1),   Null);
1855        null_test!(divide   U64(1),   Null);
1856        null_test!(divide   U128(1),   Null);
1857        null_test!(divide   F32(1.0_f32), Null);
1858        null_test!(divide   F64(1.0), Null);
1859        null_test!(divide   decimal(1), Null);
1860        null_test!(divide   mon!(1),  Null);
1861        null_test!(modulo   I8(1),    Null);
1862        null_test!(modulo   I16(1),    Null);
1863        null_test!(modulo   I32(1),    Null);
1864        null_test!(modulo   I64(1),   Null);
1865        null_test!(modulo   I128(1),   Null);
1866        null_test!(modulo   U8(1),   Null);
1867        null_test!(modulo   U16(1),   Null);
1868        null_test!(modulo   U32(1),   Null);
1869        null_test!(modulo   U64(1),   Null);
1870        null_test!(modulo   U128(1),   Null);
1871        null_test!(modulo   F32(1.0_f32), Null);
1872        null_test!(modulo   F64(1.0), Null);
1873        null_test!(modulo   decimal(1), Null);
1874
1875        null_test!(add      Null, I8(1));
1876        null_test!(add      Null, I16(1));
1877        null_test!(add      Null, I32(1));
1878        null_test!(add      Null, I64(1));
1879        null_test!(add      Null, I128(1));
1880        null_test!(add      Null, U8(1));
1881        null_test!(add      Null, U16(1));
1882        null_test!(add      Null, U32(1));
1883        null_test!(add      Null, U64(1));
1884        null_test!(add      Null, U128(1));
1885        null_test!(add      Null, F32(1.0_f32));
1886        null_test!(add      Null, F64(1.0));
1887        null_test!(add      Null, decimal(1));
1888        null_test!(add      Null, mon!(1));
1889        null_test!(add      Null, date());
1890        null_test!(add      Null, ts());
1891        null_test!(subtract Null, I8(1));
1892        null_test!(subtract Null, I16(1));
1893        null_test!(subtract Null, I32(1));
1894        null_test!(subtract Null, I64(1));
1895        null_test!(subtract Null, I128(1));
1896        null_test!(subtract Null, U8(1));
1897        null_test!(subtract Null, U16(1));
1898        null_test!(subtract Null, U32(1));
1899        null_test!(subtract Null, U64(1));
1900        null_test!(subtract Null, U128(1));
1901        null_test!(subtract Null, F32(1.0_f32));
1902        null_test!(subtract Null, F64(1.0));
1903        null_test!(subtract Null, decimal(1));
1904        null_test!(subtract Null, date());
1905        null_test!(subtract Null, ts());
1906        null_test!(subtract Null, time());
1907        null_test!(subtract Null, mon!(1));
1908        null_test!(multiply Null, I8(1));
1909        null_test!(multiply Null, I16(1));
1910        null_test!(multiply Null, I32(1));
1911        null_test!(multiply Null, I64(1));
1912        null_test!(multiply Null, I128(1));
1913        null_test!(multiply Null, U8(1));
1914        null_test!(multiply Null, U16(1));
1915        null_test!(multiply Null, U32(1));
1916        null_test!(multiply Null, U64(1));
1917        null_test!(multiply Null, U128(1));
1918        null_test!(multiply Null, F32(1.0_f32));
1919        null_test!(multiply Null, F64(1.0));
1920        null_test!(multiply Null, decimal(1));
1921        null_test!(divide   Null, I8(1));
1922        null_test!(divide   Null, I16(1));
1923        null_test!(divide   Null, I32(1));
1924        null_test!(divide   Null, I64(1));
1925        null_test!(divide   Null, I128(1));
1926        null_test!(divide   Null, U8(1));
1927        null_test!(divide   Null, U16(1));
1928        null_test!(divide   Null, U32(1));
1929        null_test!(divide   Null, U64(1));
1930        null_test!(divide   Null, U128(1));
1931        null_test!(divide   Null, F32(1.0_f32));
1932        null_test!(divide   Null, F64(1.0));
1933        null_test!(divide   Null, decimal(1));
1934        null_test!(modulo   Null, I8(1));
1935        null_test!(modulo   Null, I32(1));
1936        null_test!(modulo   Null, I64(1));
1937        null_test!(modulo   Null, I128(1));
1938        null_test!(modulo   Null, U8(1));
1939        null_test!(modulo   Null, U16(1));
1940        null_test!(modulo   Null, U32(1));
1941        null_test!(modulo   Null, U64(1));
1942        null_test!(modulo   Null, U128(1));
1943        null_test!(modulo   Null, F32(1.0_f32));
1944        null_test!(modulo   Null, F64(1.0));
1945        null_test!(modulo   Null, decimal(1));
1946
1947        null_test!(add      Null, Null);
1948        null_test!(subtract Null, Null);
1949        null_test!(multiply Null, Null);
1950        null_test!(divide   Null, Null);
1951        null_test!(modulo   Null, Null);
1952    }
1953
1954    #[test]
1955    fn bitwise_shift_left() {
1956        use {super::error::ValueError, crate::ast::DataType};
1957
1958        use utils::Tribool::True;
1959        macro_rules! test {
1960            ($op: ident $a: expr, $b: expr => $c: expr) => {
1961                assert_eq!(True, $a.$op(&$b).unwrap().evaluate_eq(&$c));
1962            };
1963        }
1964
1965        macro_rules! mon {
1966            ($n: expr) => {
1967                Interval(Interval::Month($n))
1968            };
1969        }
1970
1971        // operation result test
1972        test!(bitwise_shift_left I8(1),     I64(2) => I8(4));
1973        test!(bitwise_shift_left I16(1),    I64(2) => I16(4));
1974        test!(bitwise_shift_left I32(1),    I64(2) => I32(4));
1975        test!(bitwise_shift_left I64(1),    I64(2) => I64(4));
1976        test!(bitwise_shift_left I128(1),   I64(2) => I128(4));
1977        test!(bitwise_shift_left U8(1),     I64(2) => U8(4));
1978        test!(bitwise_shift_left U16(1),    I64(2) => U16(4));
1979        test!(bitwise_shift_left U32(1),    I64(2) => U32(4));
1980        test!(bitwise_shift_left U64(1),    I64(2) => U64(4));
1981        test!(bitwise_shift_left U128(1),   I64(2) => U128(4));
1982        test!(bitwise_shift_left I8(1),     U32(2) => I8(4));
1983        test!(bitwise_shift_left I16(1),    U32(2) => I16(4));
1984        test!(bitwise_shift_left I32(1),    U32(2) => I32(4));
1985        test!(bitwise_shift_left I64(1),    U32(2) => I64(4));
1986        test!(bitwise_shift_left I128(1),   U32(2) => I128(4));
1987        test!(bitwise_shift_left U8(1),     U32(2) => U8(4));
1988        test!(bitwise_shift_left U16(1),    U32(2) => U16(4));
1989        test!(bitwise_shift_left U32(1),    U32(2) => U32(4));
1990        test!(bitwise_shift_left U64(1),    U32(2) => U64(4));
1991        test!(bitwise_shift_left U128(1),   U32(2) => U128(4));
1992
1993        //overflow test
1994        assert_eq!(
1995            I8(1).bitwise_shift_left(&I64(100)),
1996            Err(ValueError::BinaryOperationOverflow {
1997                lhs: I8(1),
1998                rhs: U32(100),
1999                operator: NumericBinaryOperator::BitwiseShiftLeft
2000            }
2001            .into())
2002        );
2003        assert_eq!(
2004            I16(1).bitwise_shift_left(&I64(100)),
2005            Err(ValueError::BinaryOperationOverflow {
2006                lhs: I16(1),
2007                rhs: U32(100),
2008                operator: NumericBinaryOperator::BitwiseShiftLeft
2009            }
2010            .into())
2011        );
2012        assert_eq!(
2013            I32(1).bitwise_shift_left(&I64(100)),
2014            Err(ValueError::BinaryOperationOverflow {
2015                lhs: I32(1),
2016                rhs: U32(100),
2017                operator: NumericBinaryOperator::BitwiseShiftLeft
2018            }
2019            .into())
2020        );
2021        assert_eq!(
2022            I64(1).bitwise_shift_left(&I64(100)),
2023            Err(ValueError::BinaryOperationOverflow {
2024                lhs: I64(1),
2025                rhs: U32(100),
2026                operator: NumericBinaryOperator::BitwiseShiftLeft
2027            }
2028            .into())
2029        );
2030        assert_eq!(
2031            I128(1).bitwise_shift_left(&I64(150)),
2032            Err(ValueError::BinaryOperationOverflow {
2033                lhs: I128(1),
2034                rhs: U32(150),
2035                operator: NumericBinaryOperator::BitwiseShiftLeft
2036            }
2037            .into())
2038        );
2039        assert_eq!(
2040            U8(1).bitwise_shift_left(&I64(100)),
2041            Err(ValueError::BinaryOperationOverflow {
2042                lhs: U8(1),
2043                rhs: U32(100),
2044                operator: NumericBinaryOperator::BitwiseShiftLeft
2045            }
2046            .into())
2047        );
2048        assert_eq!(
2049            U16(1).bitwise_shift_left(&I64(100)),
2050            Err(ValueError::BinaryOperationOverflow {
2051                lhs: U16(1),
2052                rhs: U32(100),
2053                operator: NumericBinaryOperator::BitwiseShiftLeft
2054            }
2055            .into())
2056        );
2057        assert_eq!(
2058            U32(1).bitwise_shift_left(&I64(100)),
2059            Err(ValueError::BinaryOperationOverflow {
2060                lhs: U32(1),
2061                rhs: U32(100),
2062                operator: NumericBinaryOperator::BitwiseShiftLeft
2063            }
2064            .into())
2065        );
2066        assert_eq!(
2067            U64(1).bitwise_shift_left(&I64(100)),
2068            Err(ValueError::BinaryOperationOverflow {
2069                lhs: U64(1),
2070                rhs: U32(100),
2071                operator: NumericBinaryOperator::BitwiseShiftLeft
2072            }
2073            .into())
2074        );
2075        assert_eq!(
2076            U128(1).bitwise_shift_left(&I64(150)),
2077            Err(ValueError::BinaryOperationOverflow {
2078                lhs: U128(1),
2079                rhs: U32(150),
2080                operator: NumericBinaryOperator::BitwiseShiftLeft
2081            }
2082            .into())
2083        );
2084
2085        // cast error test
2086        assert_eq!(
2087            I64(1).bitwise_shift_left(&I64(-2)),
2088            Err(ValueError::ConvertFailed {
2089                value: I64(-2),
2090                data_type: DataType::Uint32,
2091            }
2092            .into())
2093        );
2094
2095        // non numeric test
2096        assert_eq!(
2097            mon!(3).bitwise_shift_left(&I64(2)),
2098            Err(ValueError::NonNumericMathOperation {
2099                lhs: mon!(3),
2100                rhs: U32(2),
2101                operator: NumericBinaryOperator::BitwiseShiftLeft,
2102            }
2103            .into())
2104        );
2105
2106        // null test
2107        macro_rules! null_test {
2108            ($op: ident $a: expr, $b: expr) => {
2109                assert!($a.$op(&$b).unwrap().is_null());
2110            };
2111        }
2112
2113        null_test!(bitwise_shift_left   I64(1), Null);
2114        null_test!(bitwise_shift_left   Null, I64(1));
2115    }
2116
2117    #[test]
2118    fn bitwise_shift_right() {
2119        use {super::error::ValueError, crate::ast::DataType};
2120
2121        use utils::Tribool::True;
2122        macro_rules! test {
2123            ($op: ident $a: expr, $b: expr => $c: expr) => {
2124                assert_eq!(True, $a.$op(&$b).unwrap().evaluate_eq(&$c));
2125            };
2126        }
2127
2128        macro_rules! mon {
2129            ($n: expr) => {
2130                Interval(Interval::Month($n))
2131            };
2132        }
2133
2134        // operation result test
2135        test!(bitwise_shift_right I8(1),     I64(2) => I8(0));
2136        test!(bitwise_shift_right I16(1),    I64(2) => I16(0));
2137        test!(bitwise_shift_right I32(1),    I64(2) => I32(0));
2138        test!(bitwise_shift_right I64(1),    I64(2) => I64(0));
2139        test!(bitwise_shift_right I128(1),   I64(2) => I128(0));
2140        test!(bitwise_shift_right U8(1),     I64(2) => U8(0));
2141        test!(bitwise_shift_right U16(1),    I64(2) => U16(0));
2142        test!(bitwise_shift_right U32(1),    I64(2) => U32(0));
2143        test!(bitwise_shift_right U64(1),    I64(2) => U64(0));
2144        test!(bitwise_shift_right U128(1),   I64(2) => U128(0));
2145        test!(bitwise_shift_right I8(1),     U32(2) => I8(0));
2146        test!(bitwise_shift_right I16(1),    U32(2) => I16(0));
2147        test!(bitwise_shift_right I32(1),    U32(2) => I32(0));
2148        test!(bitwise_shift_right I64(1),    U32(2) => I64(0));
2149        test!(bitwise_shift_right I128(1),   U32(2) => I128(0));
2150        test!(bitwise_shift_right U8(1),     U32(2) => U8(0));
2151        test!(bitwise_shift_right U16(1),    U32(2) => U16(0));
2152        test!(bitwise_shift_right U32(1),    U32(2) => U32(0));
2153        test!(bitwise_shift_right U64(1),    U32(2) => U64(0));
2154        test!(bitwise_shift_right U128(1),   U32(2) => U128(0));
2155
2156        //overflow test
2157        assert_eq!(
2158            I8(1).bitwise_shift_right(&I64(100)),
2159            Err(ValueError::BinaryOperationOverflow {
2160                lhs: I8(1),
2161                rhs: U32(100),
2162                operator: NumericBinaryOperator::BitwiseShiftRight
2163            }
2164            .into())
2165        );
2166        assert_eq!(
2167            I16(1).bitwise_shift_right(&I64(100)),
2168            Err(ValueError::BinaryOperationOverflow {
2169                lhs: I16(1),
2170                rhs: U32(100),
2171                operator: NumericBinaryOperator::BitwiseShiftRight
2172            }
2173            .into())
2174        );
2175        assert_eq!(
2176            I32(1).bitwise_shift_right(&I64(100)),
2177            Err(ValueError::BinaryOperationOverflow {
2178                lhs: I32(1),
2179                rhs: U32(100),
2180                operator: NumericBinaryOperator::BitwiseShiftRight
2181            }
2182            .into())
2183        );
2184        assert_eq!(
2185            I64(1).bitwise_shift_right(&I64(100)),
2186            Err(ValueError::BinaryOperationOverflow {
2187                lhs: I64(1),
2188                rhs: U32(100),
2189                operator: NumericBinaryOperator::BitwiseShiftRight
2190            }
2191            .into())
2192        );
2193        assert_eq!(
2194            I128(1).bitwise_shift_right(&I64(150)),
2195            Err(ValueError::BinaryOperationOverflow {
2196                lhs: I128(1),
2197                rhs: U32(150),
2198                operator: NumericBinaryOperator::BitwiseShiftRight
2199            }
2200            .into())
2201        );
2202        assert_eq!(
2203            U8(1).bitwise_shift_right(&I64(100)),
2204            Err(ValueError::BinaryOperationOverflow {
2205                lhs: U8(1),
2206                rhs: U32(100),
2207                operator: NumericBinaryOperator::BitwiseShiftRight
2208            }
2209            .into())
2210        );
2211        assert_eq!(
2212            U16(1).bitwise_shift_right(&I64(100)),
2213            Err(ValueError::BinaryOperationOverflow {
2214                lhs: U16(1),
2215                rhs: U32(100),
2216                operator: NumericBinaryOperator::BitwiseShiftRight
2217            }
2218            .into())
2219        );
2220        assert_eq!(
2221            U32(1).bitwise_shift_right(&I64(100)),
2222            Err(ValueError::BinaryOperationOverflow {
2223                lhs: U32(1),
2224                rhs: U32(100),
2225                operator: NumericBinaryOperator::BitwiseShiftRight
2226            }
2227            .into())
2228        );
2229        assert_eq!(
2230            U64(1).bitwise_shift_right(&I64(100)),
2231            Err(ValueError::BinaryOperationOverflow {
2232                lhs: U64(1),
2233                rhs: U32(100),
2234                operator: NumericBinaryOperator::BitwiseShiftRight
2235            }
2236            .into())
2237        );
2238        assert_eq!(
2239            U128(1).bitwise_shift_right(&I64(150)),
2240            Err(ValueError::BinaryOperationOverflow {
2241                lhs: U128(1),
2242                rhs: U32(150),
2243                operator: NumericBinaryOperator::BitwiseShiftRight
2244            }
2245            .into())
2246        );
2247
2248        // cast error test
2249        assert_eq!(
2250            I64(1).bitwise_shift_right(&I64(-2)),
2251            Err(ValueError::ConvertFailed {
2252                value: I64(-2),
2253                data_type: DataType::Uint32,
2254            }
2255            .into())
2256        );
2257
2258        // non numeric test
2259        assert_eq!(
2260            mon!(3).bitwise_shift_right(&I64(2)),
2261            Err(ValueError::NonNumericMathOperation {
2262                lhs: mon!(3),
2263                rhs: U32(2),
2264                operator: NumericBinaryOperator::BitwiseShiftRight,
2265            }
2266            .into())
2267        );
2268
2269        // null test
2270        macro_rules! null_test {
2271            ($op: ident $a: expr, $b: expr) => {
2272                assert!($a.$op(&$b).unwrap().is_null());
2273            };
2274        }
2275
2276        null_test!(bitwise_shift_right   I64(1), Null);
2277        null_test!(bitwise_shift_right   Null, I64(1));
2278    }
2279
2280    #[test]
2281    fn cast() {
2282        use {
2283            crate::{ast::DataType::*, data::Point, prelude::Value},
2284            chrono::{NaiveDate, NaiveTime},
2285        };
2286
2287        macro_rules! cast {
2288            ($input: expr => $data_type: expr, $expected: expr) => {
2289                let found = $input.cast(&$data_type).unwrap();
2290
2291                match ($expected, found) {
2292                    (Null, Null) => {}
2293                    (expected, found) => {
2294                        assert_eq!(expected, found);
2295                    }
2296                }
2297            };
2298        }
2299
2300        let bytea = Value::Bytea(hex::decode("0abc").unwrap());
2301        let inet = |v| Value::Inet(IpAddr::from_str(v).unwrap());
2302        let point = |x, y| Value::Point(Point::new(x, y));
2303
2304        // Same as
2305        cast!(Bool(true)            => Boolean      , Bool(true));
2306        cast!(Str("a".to_owned())   => Text         , Str("a".to_owned()));
2307        cast!(bytea                 => Bytea        , bytea);
2308        cast!(inet("::1")           => Inet         , inet("::1"));
2309        cast!(I8(1)                 => Int8         , I8(1));
2310        cast!(I16(1)                 => Int16         , I16(1));
2311        cast!(I32(1)                => Int32        , I32(1));
2312        cast!(I64(1)                => Int          , I64(1));
2313        cast!(I128(1)               => Int128       , I128(1));
2314        cast!(U8(1)                 => Uint8        , U8(1));
2315        cast!(U16(1)                 => Uint16        , U16(1));
2316        cast!(U32(1)                 => Uint32        , U32(1));
2317        cast!(U64(1)                 => Uint64        , U64(1));
2318        cast!(U128(1)                 => Uint128        , U128(1));
2319        cast!(F32(1.0_f32)              => Float32        , F32(1.0_f32));
2320        cast!(F64(1.0)              => Float        , F64(1.0));
2321        cast!(Value::Uuid(123)      => Uuid         , Value::Uuid(123));
2322
2323        // Boolean
2324        cast!(Str("TRUE".to_owned())    => Boolean, Bool(true));
2325        cast!(Str("FALSE".to_owned())   => Boolean, Bool(false));
2326        cast!(I8(1)                     => Boolean, Bool(true));
2327        cast!(I8(0)                     => Boolean, Bool(false));
2328        cast!(I16(0)                     => Boolean, Bool(false));
2329        cast!(I32(1)                     => Boolean, Bool(true));
2330        cast!(I32(0)                     => Boolean, Bool(false));
2331        cast!(I64(1)                    => Boolean, Bool(true));
2332        cast!(I64(0)                    => Boolean, Bool(false));
2333        cast!(I128(1)                   => Boolean, Bool(true));
2334        cast!(I128(0)                   => Boolean, Bool(false));
2335        cast!(U8(1)                   => Boolean, Bool(true));
2336        cast!(U8(0)                   => Boolean, Bool(false));
2337        cast!(U16(1)                   => Boolean, Bool(true));
2338        cast!(U16(0)                   => Boolean, Bool(false));
2339        cast!(U32(1)                   => Boolean, Bool(true));
2340        cast!(U32(1)                   => Boolean, Bool(true));
2341        cast!(U64(1)                   => Boolean, Bool(true));
2342        cast!(U64(0)                   => Boolean, Bool(false));
2343        cast!(U128(0)                   => Boolean, Bool(false));
2344        cast!(U128(0)                   => Boolean, Bool(false));
2345        cast!(F32(1.0_f32)                  => Boolean, Bool(true));
2346        cast!(F32(0.0_f32)                  => Boolean, Bool(false));
2347        cast!(F64(1.0)                  => Boolean, Bool(true));
2348        cast!(F64(0.0)                  => Boolean, Bool(false));
2349        cast!(Null                      => Boolean, Null);
2350
2351        // Integer
2352        cast!(Bool(true)            => Int8, I8(1));
2353        cast!(Bool(false)           => Int8, I8(0));
2354        cast!(F32(1.1_f32)              => Int8, I8(1));
2355        cast!(F64(1.1)              => Int8, I8(1));
2356        cast!(Str("11".to_owned())  => Int8, I8(11));
2357        cast!(Null                  => Int8, Null);
2358
2359        cast!(Bool(true)            => Int32, I32(1));
2360        cast!(Bool(false)           => Int32, I32(0));
2361        cast!(F32(1.1_f32)              => Int32, I32(1));
2362        cast!(F64(1.1)              => Int32, I32(1));
2363        cast!(Str("11".to_owned())  => Int32, I32(11));
2364        cast!(Null                  => Int32, Null);
2365
2366        cast!(Bool(true)            => Int, I64(1));
2367        cast!(Bool(false)           => Int, I64(0));
2368        cast!(F32(1.1_f32)              => Int, I64(1));
2369        cast!(F64(1.1)              => Int, I64(1));
2370        cast!(Str("11".to_owned())  => Int, I64(11));
2371        cast!(Null                  => Int, Null);
2372
2373        cast!(Bool(true)            => Int128, I128(1));
2374        cast!(Bool(false)           => Int128, I128(0));
2375        cast!(F32(1.1_f32)          => Int128, I128(1));
2376        cast!(F64(1.1)              => Int128, I128(1));
2377        cast!(Str("11".to_owned())  => Int128, I128(11));
2378        cast!(Null                  => Int128, Null);
2379
2380        cast!(Bool(true)            => Uint8, U8(1));
2381        cast!(Bool(false)           => Uint8, U8(0));
2382        cast!(F32(1.1_f32)              => Uint8, U8(1));
2383        cast!(F64(1.1)              => Uint8, U8(1));
2384        cast!(Str("11".to_owned())  => Uint8, U8(11));
2385        cast!(Null                  => Uint8, Null);
2386
2387        cast!(Bool(true)            => Uint16, U16(1));
2388        cast!(Bool(false)           => Uint16, U16(0));
2389        cast!(F32(1.1_f32)              => Uint16, U16(1));
2390        cast!(F64(1.1)              => Uint16, U16(1));
2391        cast!(Str("11".to_owned())  => Uint16, U16(11));
2392        cast!(Null                  => Uint16, Null);
2393
2394        cast!(Bool(true)            => Uint32, U32(1));
2395        cast!(Bool(false)           => Uint32, U32(0));
2396        cast!(F32(1.1_f32)              => Uint32, U32(1));
2397        cast!(F64(1.1)              => Uint32, U32(1));
2398        cast!(Str("11".to_owned())  => Uint32, U32(11));
2399        cast!(Null                  => Uint32, Null);
2400
2401        cast!(Bool(true)            => Uint64, U64(1));
2402        cast!(Bool(false)           => Uint64, U64(0));
2403        cast!(F32(1.1_f32)              => Uint64, U64(1));
2404        cast!(F64(1.1)              => Uint64, U64(1));
2405        cast!(Str("11".to_owned())  => Uint64, U64(11));
2406        cast!(Null                  => Uint64, Null);
2407
2408        cast!(Bool(true)            => Uint128, U128(1));
2409        cast!(Bool(false)           => Uint128, U128(0));
2410        cast!(F32(1.1_f32)              => Uint128, U128(1));
2411        cast!(F64(1.1)              => Uint128, U128(1));
2412        cast!(Str("11".to_owned())  => Uint128, U128(11));
2413        cast!(Null                  => Uint128, Null);
2414
2415        // Float32
2416        cast!(Bool(true)            => Float32, F32(1.0_f32));
2417        cast!(Bool(false)           => Float32, F32(0.0_f32));
2418        cast!(I8(1)                 => Float32, F32(1.0_f32));
2419        cast!(I16(1)                 => Float32, F32(1.0_f32));
2420        cast!(I32(1)                => Float32, F32(1.0_f32));
2421        cast!(I64(1)                => Float32, F32(1.0_f32));
2422        cast!(I128(1)               => Float32, F32(1.0_f32));
2423        cast!(F64(1.0)               => Float32, F32(1.0_f32));
2424
2425        // Float
2426        cast!(Bool(true)            => Float, F64(1.0));
2427        cast!(Bool(false)           => Float, F64(0.0));
2428        cast!(I8(1)                 => Float, F64(1.0));
2429        cast!(I16(1)                 => Float, F64(1.0));
2430        cast!(I32(1)                => Float, F64(1.0));
2431        cast!(I64(1)                => Float, F64(1.0));
2432        cast!(I128(1)               => Float, F64(1.0));
2433        cast!(F32(1_f32)               => Float, F64(1.0));
2434
2435        cast!(U8(1)                 => Float, F64(1.0));
2436        cast!(U16(1)                 => Float, F64(1.0));
2437        cast!(U32(1)                 => Float, F64(1.0));
2438        cast!(U64(1)                 => Float, F64(1.0));
2439        cast!(U128(1)                 => Float, F64(1.0));
2440        cast!(Str("11".to_owned())  => Float, F64(11.0));
2441        cast!(Null                  => Float, Null);
2442
2443        // Text
2444        cast!(Bool(true)    => Text, Str("TRUE".to_owned()));
2445        cast!(Bool(false)   => Text, Str("FALSE".to_owned()));
2446        cast!(I8(11)        => Text, Str("11".to_owned()));
2447        cast!(I16(11)        => Text, Str("11".to_owned()));
2448        cast!(I32(11)        => Text, Str("11".to_owned()));
2449        cast!(I64(11)       => Text, Str("11".to_owned()));
2450        cast!(I128(11)        => Text, Str("11".to_owned()));
2451        cast!(U8(11)        => Text, Str("11".to_owned()));
2452        cast!(U16(11)        => Text, Str("11".to_owned()));
2453        cast!(U32(11)        => Text, Str("11".to_owned()));
2454        cast!(U64(11)        => Text, Str("11".to_owned()));
2455        cast!(U128(11)        => Text, Str("11".to_owned()));
2456        cast!(F32(1.0_f32)      => Text, Str("1".to_owned()));
2457        cast!(F64(1.0)      => Text, Str("1".to_owned()));
2458        cast!(inet("::1")    => Text, Str("::1".to_owned()));
2459
2460        let date = Value::Date(NaiveDate::from_ymd_opt(2021, 5, 1).unwrap());
2461        cast!(date          => Text, Str("2021-05-01".to_owned()));
2462
2463        let timestamp = Value::Timestamp(
2464            NaiveDate::from_ymd_opt(2021, 5, 1)
2465                .unwrap()
2466                .and_hms_opt(12, 34, 50)
2467                .unwrap(),
2468        );
2469        cast!(timestamp     => Text, Str("2021-05-01 12:34:50".to_owned()));
2470        cast!(Null          => Text, Null);
2471
2472        // Date
2473        let date = Value::Date(NaiveDate::from_ymd_opt(2021, 5, 1).unwrap());
2474        let timestamp = Value::Timestamp(
2475            NaiveDate::from_ymd_opt(2021, 5, 1)
2476                .unwrap()
2477                .and_hms_opt(12, 34, 50)
2478                .unwrap(),
2479        );
2480
2481        cast!(Str("2021-05-01".to_owned()) => Date, date.clone());
2482        cast!(timestamp                    => Date, date);
2483        cast!(Null                         => Date, Null);
2484
2485        // Time
2486        cast!(Str("08:05:30".to_owned()) => Time, Value::Time(NaiveTime::from_hms_opt(8, 5, 30).unwrap()));
2487        cast!(Null                       => Time, Null);
2488
2489        // Timestamp
2490        cast!(Value::Date(NaiveDate::from_ymd_opt(2021, 5, 1).unwrap()) => Timestamp, Value::Timestamp(NaiveDate::from_ymd_opt(2021, 5, 1).unwrap().and_hms_opt(0, 0, 0).unwrap()));
2491        cast!(Str("2021-05-01 08:05:30".to_owned())                     => Timestamp, Value::Timestamp(NaiveDate::from_ymd_opt(2021, 5, 1).unwrap().and_hms_opt(8, 5, 30).unwrap()));
2492        cast!(Null                                                      => Timestamp, Null);
2493
2494        // Bytea
2495        cast!(Value::Str("0abc".to_owned()) => Bytea, Value::Bytea(hex::decode("0abc").unwrap()));
2496        assert_eq!(
2497            Value::Str("!@#$5".to_owned()).cast(&Bytea),
2498            Err(ValueError::CastFromHexToByteaFailed("!@#$5".to_owned()).into()),
2499        );
2500
2501        // Inet
2502        cast!(inet("::1") => Inet, inet("::1"));
2503        cast!(Str("::1".to_owned()) => Inet, inet("::1"));
2504        cast!(Str("0.0.0.0".to_owned()) => Inet, inet("0.0.0.0"));
2505
2506        // Point
2507        cast!(point(0.32, 0.52) => Point, point(0.32, 0.52));
2508        cast!(Str("POINT(0.32 0.52)".to_owned()) => Point, point(0.32, 0.52));
2509
2510        // Map
2511        cast!(
2512            Str(r#"{"a": 1}"#.to_owned()) => Map,
2513            Value::parse_json_map(r#"{"a": 1}"#).unwrap()
2514        );
2515
2516        // List
2517        cast!(
2518            Str(r"[1, 2, 3]".to_owned()) => List,
2519            Value::parse_json_list(r"[1, 2, 3]").unwrap()
2520        );
2521
2522        // Casting error
2523        assert_eq!(
2524            Value::Uuid(123).cast(&List),
2525            Err(ValueError::UnimplementedCast {
2526                value: Value::Uuid(123),
2527                data_type: List,
2528            }
2529            .into())
2530        );
2531    }
2532
2533    #[test]
2534    fn concat() {
2535        assert_eq!(
2536            Str("A".to_owned()).concat(Str("B".to_owned())),
2537            Str("AB".to_owned())
2538        );
2539        assert_eq!(
2540            Str("A".to_owned()).concat(Bool(true)),
2541            Str("ATRUE".to_owned())
2542        );
2543        assert_eq!(Str("A".to_owned()).concat(I8(1)), Str("A1".to_owned()));
2544        assert_eq!(Str("A".to_owned()).concat(I16(1)), Str("A1".to_owned()));
2545        assert_eq!(Str("A".to_owned()).concat(I32(1)), Str("A1".to_owned()));
2546        assert_eq!(Str("A".to_owned()).concat(I64(1)), Str("A1".to_owned()));
2547        assert_eq!(Str("A".to_owned()).concat(I128(1)), Str("A1".to_owned()));
2548        assert_eq!(Str("A".to_owned()).concat(U8(1)), Str("A1".to_owned()));
2549        assert_eq!(Str("A".to_owned()).concat(U16(1)), Str("A1".to_owned()));
2550        assert_eq!(Str("A".to_owned()).concat(U32(1)), Str("A1".to_owned()));
2551        assert_eq!(Str("A".to_owned()).concat(U64(1)), Str("A1".to_owned()));
2552        assert_eq!(Str("A".to_owned()).concat(U128(1)), Str("A1".to_owned()));
2553        assert_eq!(
2554            Str("A".to_owned()).concat(F32(1.0_f32)),
2555            Str("A1".to_owned())
2556        );
2557        assert_eq!(Str("A".to_owned()).concat(F64(1.0)), Str("A1".to_owned()));
2558        assert_eq!(
2559            List(vec![I64(1)]).concat(List(vec![I64(2)])),
2560            List(vec![I64(1), I64(2)])
2561        );
2562        assert_eq!(I64(2).concat(I64(1)), Str("21".to_owned()));
2563        assert!(Str("A".to_owned()).concat(Null).is_null());
2564    }
2565
2566    #[test]
2567    fn validate_type() {
2568        use {
2569            super::{Value, ValueError},
2570            crate::{ast::DataType as D, data::Interval as I, data::Point},
2571            chrono::{NaiveDate, NaiveTime},
2572        };
2573
2574        let date = Date(NaiveDate::from_ymd_opt(2021, 5, 1).unwrap());
2575        let timestamp = Timestamp(
2576            NaiveDate::from_ymd_opt(2021, 5, 1)
2577                .unwrap()
2578                .and_hms_opt(12, 34, 50)
2579                .unwrap(),
2580        );
2581        let time = Time(NaiveTime::from_hms_opt(12, 30, 11).unwrap());
2582        let interval = Interval(I::hours(5));
2583        let uuid = Uuid(parse_uuid("936DA01F9ABD4d9d80C702AF85C822A8").unwrap());
2584        let point = Point(Point::new(1.0, 2.0));
2585        let map = Value::parse_json_map(r#"{ "a": 10 }"#).unwrap();
2586        let list = Value::parse_json_list(r"[ true ]").unwrap();
2587        let bytea = Bytea(hex::decode("9001").unwrap());
2588        let inet = Inet(IpAddr::from_str("::1").unwrap());
2589
2590        assert!(Bool(true).validate_type(&D::Boolean).is_ok());
2591        assert!(Bool(true).validate_type(&D::Int).is_err());
2592        assert!(I8(1).validate_type(&D::Int8).is_ok());
2593        assert!(I8(1).validate_type(&D::Text).is_err());
2594        assert!(I16(1).validate_type(&D::Text).is_err());
2595        assert!(I32(1).validate_type(&D::Int32).is_ok());
2596        assert!(I32(1).validate_type(&D::Text).is_err());
2597        assert!(I64(1).validate_type(&D::Int).is_ok());
2598        assert!(I64(1).validate_type(&D::Text).is_err());
2599        assert!(I128(1).validate_type(&D::Int128).is_ok());
2600        assert!(I128(1).validate_type(&D::Text).is_err());
2601        assert!(U8(1).validate_type(&D::Uint8).is_ok());
2602        assert!(U8(1).validate_type(&D::Text).is_err());
2603        assert!(U16(1).validate_type(&D::Uint16).is_ok());
2604        assert!(U16(1).validate_type(&D::Text).is_err());
2605        assert!(U32(1).validate_type(&D::Uint32).is_ok());
2606        assert!(U32(1).validate_type(&D::Text).is_err());
2607        assert!(U64(1).validate_type(&D::Uint64).is_ok());
2608        assert!(U64(1).validate_type(&D::Text).is_err());
2609        assert!(U128(1).validate_type(&D::Uint128).is_ok());
2610        assert!(U128(1).validate_type(&D::Text).is_err());
2611        assert!(F32(1.0_f32).validate_type(&D::Float32).is_ok());
2612        assert!(F32(1.0_f32).validate_type(&D::Int).is_err());
2613        assert!(F64(1.0).validate_type(&D::Float).is_ok());
2614        assert!(F64(1.0).validate_type(&D::Int).is_err());
2615        assert!(
2616            Decimal(rust_decimal::Decimal::ONE)
2617                .validate_type(&D::Decimal)
2618                .is_ok()
2619        );
2620        assert!(
2621            Decimal(rust_decimal::Decimal::ONE)
2622                .validate_type(&D::Int)
2623                .is_err()
2624        );
2625        assert!(Str("a".to_owned()).validate_type(&D::Text).is_ok());
2626        assert!(Str("a".to_owned()).validate_type(&D::Int).is_err());
2627        assert!(bytea.validate_type(&D::Bytea).is_ok());
2628        assert!(bytea.validate_type(&D::Uuid).is_err());
2629        assert!(inet.validate_type(&D::Inet).is_ok());
2630        assert!(inet.validate_type(&D::Uuid).is_err());
2631        assert!(inet.validate_type(&D::Inet).is_ok());
2632        assert!(inet.validate_type(&D::Uuid).is_err());
2633        assert!(date.validate_type(&D::Date).is_ok());
2634        assert!(date.validate_type(&D::Text).is_err());
2635        assert!(timestamp.validate_type(&D::Timestamp).is_ok());
2636        assert!(timestamp.validate_type(&D::Boolean).is_err());
2637        assert!(time.validate_type(&D::Time).is_ok());
2638        assert!(time.validate_type(&D::Date).is_err());
2639        assert!(interval.validate_type(&D::Interval).is_ok());
2640        assert!(interval.validate_type(&D::Date).is_err());
2641        assert!(uuid.validate_type(&D::Uuid).is_ok());
2642        assert!(uuid.validate_type(&D::Boolean).is_err());
2643        assert!(point.validate_type(&D::Point).is_ok());
2644        assert!(point.validate_type(&D::Boolean).is_err());
2645        assert!(map.validate_type(&D::Map).is_ok());
2646        assert!(map.validate_type(&D::Int).is_err());
2647        assert!(list.validate_type(&D::List).is_ok());
2648        assert!(list.validate_type(&D::Int).is_err());
2649        assert!(Null.validate_type(&D::Time).is_ok());
2650        assert!(Null.validate_type(&D::Boolean).is_ok());
2651
2652        assert_eq!(
2653            Bool(true).validate_type(&D::Text),
2654            Err(ValueError::IncompatibleDataType {
2655                data_type: D::Text,
2656                value: Bool(true),
2657            }
2658            .into()),
2659        );
2660    }
2661
2662    #[test]
2663    fn unary_minus() {
2664        use crate::data::Interval as I;
2665        assert_eq!(I8(1).unary_minus(), Ok(I8(-1)));
2666        assert_eq!(I16(1).unary_minus(), Ok(I16(-1)));
2667        assert_eq!(I32(1).unary_minus(), Ok(I32(-1)));
2668        assert_eq!(I64(1).unary_minus(), Ok(I64(-1)));
2669        assert_eq!(I128(1).unary_minus(), Ok(I128(-1)));
2670
2671        assert_eq!(F32(1.0_f32).unary_minus(), Ok(F32(-1.0)));
2672        assert_eq!(F64(1.0).unary_minus(), Ok(F64(-1.0)));
2673        assert_eq!(
2674            Interval(I::hours(5)).unary_minus(),
2675            Ok(Interval(I::hours(-5)))
2676        );
2677        assert_eq!(Null.unary_minus(), Ok(Null));
2678        assert_eq!(
2679            Decimal(Decimal::ONE).unary_minus(),
2680            Ok(Decimal(-Decimal::ONE))
2681        );
2682
2683        assert_eq!(
2684            Str("abc".to_owned()).unary_minus(),
2685            Err(ValueError::UnaryMinusOnNonNumeric.into())
2686        );
2687    }
2688
2689    #[test]
2690    fn unary_plus() {
2691        assert_eq!(U8(1).unary_plus(), Ok(U8(1)));
2692        assert!(Null.unary_plus().unwrap().is_null());
2693    }
2694
2695    #[test]
2696    fn factorial() {
2697        assert_eq!(I8(5).unary_factorial(), Ok(I128(120)));
2698        assert_eq!(I16(5).unary_factorial(), Ok(I128(120)));
2699        assert_eq!(I32(5).unary_factorial(), Ok(I128(120)));
2700        assert_eq!(I64(5).unary_factorial(), Ok(I128(120)));
2701        assert_eq!(I128(5).unary_factorial(), Ok(I128(120)));
2702        assert_eq!(U8(5).unary_factorial(), Ok(I128(120)));
2703        assert_eq!(U16(5).unary_factorial(), Ok(I128(120)));
2704        assert_eq!(U32(5).unary_factorial(), Ok(I128(120)));
2705        assert_eq!(U64(5).unary_factorial(), Ok(I128(120)));
2706        assert_eq!(U128(5).unary_factorial(), Ok(I128(120)));
2707        assert_eq!(
2708            F32(5.0_f32).unary_factorial(),
2709            Err(ValueError::FactorialOnNonInteger.into())
2710        );
2711        assert_eq!(
2712            F64(5.0).unary_factorial(),
2713            Err(ValueError::FactorialOnNonInteger.into())
2714        );
2715        assert!(Null.unary_factorial().unwrap().is_null());
2716        assert_eq!(
2717            Str("5".to_owned()).unary_factorial(),
2718            Err(ValueError::FactorialOnNonNumeric.into())
2719        );
2720    }
2721
2722    #[test]
2723    fn sqrt() {
2724        assert_eq!(I8(9).sqrt(), Ok(F64(3.0)));
2725        assert_eq!(I16(9).sqrt(), Ok(F64(3.0)));
2726        assert_eq!(I64(9).sqrt(), Ok(F64(3.0)));
2727        assert_eq!(I128(9).sqrt(), Ok(F64(3.0)));
2728        assert_eq!(U8(9).sqrt(), Ok(F64(3.0)));
2729        assert_eq!(U16(9).sqrt(), Ok(F64(3.0)));
2730        assert_eq!(U32(9).sqrt(), Ok(F64(3.0)));
2731        assert_eq!(U64(9).sqrt(), Ok(F64(3.0)));
2732        assert_eq!(U128(9).sqrt(), Ok(F64(3.0)));
2733        assert_eq!(F32(9.0_f32).sqrt(), Ok(F64(3.0)));
2734        assert_eq!(F64(9.0).sqrt(), Ok(F64(3.0)));
2735        assert!(Null.sqrt().unwrap().is_null());
2736        assert_eq!(
2737            Str("9".to_owned()).sqrt(),
2738            Err(ValueError::SqrtOnNonNumeric(Str("9".to_owned())).into())
2739        );
2740    }
2741
2742    #[test]
2743    fn bitwise_and() {
2744        use utils::Tribool::True;
2745        macro_rules! test {
2746            ($op: ident $a: expr, $b: expr => $c: expr) => {
2747                assert_eq!(True, $a.$op(&$b).unwrap().evaluate_eq(&$c));
2748            };
2749        }
2750
2751        macro_rules! test_bitwise_and {
2752            ($($vt: ident $pt: ident);*;) => {
2753                $(
2754                    test!(bitwise_and $vt($pt::MIN), $vt($pt::MIN) => $vt($pt::MIN & $pt::MIN));
2755                    test!(bitwise_and $vt($pt::MIN), $vt($pt::MAX) => $vt($pt::MIN & $pt::MAX));
2756                    test!(bitwise_and $vt($pt::MAX), $vt($pt::MAX) => $vt($pt::MAX & $pt::MAX));
2757                    test!(bitwise_and $vt(0), $vt(0) => $vt(0 & 0));
2758                    test!(bitwise_and $vt(0), $vt(1) => $vt(0 & 1));
2759                    test!(bitwise_and $vt(1), $vt(0) => $vt(1 & 0));
2760                    test!(bitwise_and $vt(1), $vt(1) => $vt(1 & 1));
2761                )*
2762            };
2763        }
2764
2765        test_bitwise_and!(
2766            I8      i8;
2767            I16     i16;
2768            I32     i32;
2769            I64     i64;
2770            I128    i128;
2771            U8      u8;
2772            U16     u16;
2773            U32     u32;
2774            U64     u64;
2775            U128    u128;
2776        );
2777
2778        macro_rules! null_test {
2779            ($op: ident $a: expr, $b: expr) => {
2780                assert!($a.$op(&$b).unwrap().is_null());
2781            };
2782        }
2783
2784        macro_rules! null_test_bitwise_and {
2785            ($($vt: ident)*) => {
2786                $(
2787                    null_test!(bitwise_and $vt(1), Null);
2788                    null_test!(bitwise_and Null, $vt(1));
2789                    null_test!(bitwise_and Null, Null);
2790                )*
2791            };
2792        }
2793
2794        null_test_bitwise_and!(
2795            I8 I16 I32 I64 I128 U8 U16 U32 U64 U128
2796        );
2797
2798        let lhs = I8(3);
2799        let rhs = I16(12);
2800        assert_eq!(
2801            lhs.bitwise_and(&rhs),
2802            Err(ValueError::NonNumericMathOperation {
2803                lhs,
2804                rhs,
2805                operator: NumericBinaryOperator::BitwiseAnd
2806            }
2807            .into())
2808        );
2809    }
2810
2811    #[test]
2812    fn position() {
2813        let str1 = Str("ramen".to_owned());
2814        let str2 = Str("men".to_owned());
2815        let empty_str = Str(String::new());
2816
2817        assert_eq!(str1.position(&str2), Ok(I64(3)));
2818        assert_eq!(str2.position(&str1), Ok(I64(0)));
2819        assert!(Null.position(&str2).unwrap().is_null());
2820        assert!(str1.position(&Null).unwrap().is_null());
2821        assert_eq!(empty_str.position(&str2), Ok(I64(0)));
2822        assert_eq!(str1.position(&empty_str), Ok(I64(0)));
2823        assert_eq!(
2824            str1.position(&I64(1)),
2825            Err(ValueError::NonStringParameterInPosition {
2826                from: str1,
2827                sub: I64(1)
2828            }
2829            .into())
2830        );
2831    }
2832
2833    #[test]
2834    fn get_type() {
2835        use {
2836            super::Value,
2837            crate::{ast::DataType as D, data::Interval as I, data::Point},
2838            chrono::{NaiveDate, NaiveTime},
2839        };
2840
2841        let decimal = Decimal(rust_decimal::Decimal::ONE);
2842        let date = Date(NaiveDate::from_ymd_opt(2021, 5, 1).unwrap());
2843        let timestamp = Timestamp(
2844            NaiveDate::from_ymd_opt(2021, 5, 1)
2845                .unwrap()
2846                .and_hms_opt(12, 34, 50)
2847                .unwrap(),
2848        );
2849        let time = Time(NaiveTime::from_hms_opt(12, 30, 11).unwrap());
2850        let interval = Interval(I::hours(5));
2851        let uuid = Uuid(parse_uuid("936DA01F9ABD4d9d80C702AF85C822A8").unwrap());
2852        let point = Point(Point::new(1.0, 2.0));
2853        let map = Value::parse_json_map(r#"{ "a": 10 }"#).unwrap();
2854        let list = Value::parse_json_list(r"[ true ]").unwrap();
2855        let bytea = Bytea(hex::decode("9001").unwrap());
2856        let inet = Inet(IpAddr::from_str("::1").unwrap());
2857
2858        assert_eq!(I8(1).get_type(), Some(D::Int8));
2859        assert_eq!(I16(1).get_type(), Some(D::Int16));
2860        assert_eq!(I32(1).get_type(), Some(D::Int32));
2861        assert_eq!(I64(1).get_type(), Some(D::Int));
2862        assert_eq!(I128(1).get_type(), Some(D::Int128));
2863        assert_eq!(U8(1).get_type(), Some(D::Uint8));
2864        assert_eq!(U16(1).get_type(), Some(D::Uint16));
2865        assert_eq!(U32(1).get_type(), Some(D::Uint32));
2866        assert_eq!(U64(1).get_type(), Some(D::Uint64));
2867        assert_eq!(U128(1).get_type(), Some(D::Uint128));
2868        assert_eq!(F32(1.1_f32).get_type(), Some(D::Float32));
2869        assert_eq!(F64(1.1).get_type(), Some(D::Float));
2870        assert_eq!(decimal.get_type(), Some(D::Decimal));
2871        assert_eq!(Bool(true).get_type(), Some(D::Boolean));
2872        assert_eq!(Str('1'.into()).get_type(), Some(D::Text));
2873        assert_eq!(bytea.get_type(), Some(D::Bytea));
2874        assert_eq!(inet.get_type(), Some(D::Inet));
2875        assert_eq!(date.get_type(), Some(D::Date));
2876        assert_eq!(timestamp.get_type(), Some(D::Timestamp));
2877        assert_eq!(time.get_type(), Some(D::Time));
2878        assert_eq!(interval.get_type(), Some(D::Interval));
2879        assert_eq!(uuid.get_type(), Some(D::Uuid));
2880        assert_eq!(point.get_type(), Some(D::Point));
2881        assert_eq!(map.get_type(), Some(D::Map));
2882        assert_eq!(list.get_type(), Some(D::List));
2883        assert_eq!(Null.get_type(), None);
2884    }
2885
2886    #[test]
2887    fn hash() {
2888        use {
2889            super::Interval,
2890            crate::data::point::Point,
2891            chrono::{NaiveDate, NaiveTime},
2892            rust_decimal::Decimal,
2893            std::{
2894                collections::BTreeMap,
2895                collections::hash_map::DefaultHasher,
2896                f32::consts::PI as PI_F32,
2897                f64::consts::PI as PI_F64,
2898                hash::{Hash, Hasher},
2899                net::IpAddr,
2900                str::FromStr,
2901            },
2902        };
2903
2904        fn hash_value<T: Hash>(t: &T) -> u64 {
2905            let mut hasher = DefaultHasher::new();
2906            t.hash(&mut hasher);
2907            hasher.finish()
2908        }
2909
2910        const CANONICAL_F64_NAN_BITS: u64 = 0x7ff8_0000_0000_0000;
2911        const CANONICAL_F32_NAN_BITS: u32 = 0x7fc0_0000;
2912        const CANONICAL_F32_ZERO_BITS: u32 = 0;
2913        const CANONICAL_F64_ZERO_BITS: u64 = 0;
2914
2915        // Float zero normalization: 0.0 and -0.0 should hash the same
2916        let zero_pos_f32 = F32(0.0);
2917        let zero_neg_f32 = F32(-0.0);
2918        assert_eq!(hash_value(&zero_pos_f32), hash_value(&zero_neg_f32),);
2919
2920        let zero_pos_f64 = F64(0.0);
2921        let zero_neg_f64 = F64(-0.0);
2922        assert_eq!(hash_value(&zero_pos_f64), hash_value(&zero_neg_f64),);
2923
2924        // Non-zero floats should hash differently
2925        let one_f32 = F32(1.0);
2926        let neg_one_f32 = F32(-1.0);
2927        assert_ne!(hash_value(&one_f32), hash_value(&neg_one_f32),);
2928
2929        let one_f64 = F64(1.0);
2930        let neg_one_f64 = F64(-1.0);
2931        assert_ne!(hash_value(&one_f64), hash_value(&neg_one_f64),);
2932
2933        let values_equal = [
2934            (I8(42), I8(42)),
2935            (I16(42), I16(42)),
2936            (I32(42), I32(42)),
2937            (I64(42), I64(42)),
2938            (I128(42), I128(42)),
2939            (U8(42), U8(42)),
2940            (U16(42), U16(42)),
2941            (U32(42), U32(42)),
2942            (U64(42), U64(42)),
2943            (U128(42), U128(42)),
2944            (F32(PI_F32), F32(PI_F32)),
2945            (F64(PI_F64), F64(PI_F64)),
2946            (Decimal(Decimal::new(314, 2)), Decimal(Decimal::new(314, 2))),
2947            (Bool(true), Bool(true)),
2948            (Bool(false), Bool(false)),
2949            (Str("test".to_owned()), Str("test".to_owned())),
2950            (Bytea(vec![1, 2, 3]), Bytea(vec![1, 2, 3])),
2951            (
2952                Inet(IpAddr::from_str("127.0.0.1").unwrap()),
2953                Inet(IpAddr::from_str("127.0.0.1").unwrap()),
2954            ),
2955            (
2956                Inet(IpAddr::from_str("::1").unwrap()),
2957                Inet(IpAddr::from_str("::1").unwrap()),
2958            ),
2959            (
2960                Date(NaiveDate::from_ymd_opt(2025, 8, 6).unwrap()),
2961                Date(NaiveDate::from_ymd_opt(2025, 8, 6).unwrap()),
2962            ),
2963            (
2964                Timestamp(
2965                    NaiveDate::from_ymd_opt(2025, 8, 6)
2966                        .unwrap()
2967                        .and_hms_opt(10, 30, 0)
2968                        .unwrap(),
2969                ),
2970                Timestamp(
2971                    NaiveDate::from_ymd_opt(2025, 8, 6)
2972                        .unwrap()
2973                        .and_hms_opt(10, 30, 0)
2974                        .unwrap(),
2975                ),
2976            ),
2977            (
2978                Time(NaiveTime::from_hms_opt(10, 30, 0).unwrap()),
2979                Time(NaiveTime::from_hms_opt(10, 30, 0).unwrap()),
2980            ),
2981            (Interval(Interval::hours(5)), Interval(Interval::hours(5))),
2982            (Uuid(123_456_789), Uuid(123_456_789)),
2983            (List(vec![I64(1), I64(2)]), List(vec![I64(1), I64(2)])),
2984            (Null, Null),
2985        ];
2986
2987        for (a, b) in values_equal {
2988            assert_eq!(a, b);
2989            assert_eq!(hash_value(&a), hash_value(&b), "{a:?} vs {b:?}");
2990        }
2991
2992        let map_test_cases = [{
2993            let mut map1 = BTreeMap::new();
2994            map1.insert("b".to_owned(), I64(2));
2995            map1.insert("a".to_owned(), I64(1));
2996
2997            let mut map2 = BTreeMap::new();
2998            map2.insert("a".to_owned(), I64(1));
2999            map2.insert("b".to_owned(), I64(2));
3000
3001            (super::Value::Map(map1), super::Value::Map(map2))
3002        }];
3003
3004        for (value_map1, value_map2) in map_test_cases {
3005            assert_eq!(value_map1, value_map2);
3006            assert_eq!(hash_value(&value_map1), hash_value(&value_map2));
3007        }
3008
3009        let point_test_cases = [
3010            (Point(Point::new(1.0, 2.0)), Point(Point::new(1.0, 2.0))),
3011            (Point(Point::new(0.0, 1.0)), Point(Point::new(-0.0, 1.0))),
3012            (Point(Point::new(1.0, 0.0)), Point(Point::new(1.0, -0.0))),
3013            (
3014                Point(Point::new(1.0, f64::NAN)),
3015                Point(Point::new(1.0, f64::from_bits(CANONICAL_F64_NAN_BITS))),
3016            ),
3017            (
3018                Point(Point::new(f64::NAN, 1.0)),
3019                Point(Point::new(f64::from_bits(CANONICAL_F64_NAN_BITS), 1.0)),
3020            ),
3021            (
3022                Point(Point::new(f64::NAN, f64::NAN)),
3023                Point(Point::new(
3024                    f64::from_bits(CANONICAL_F64_NAN_BITS),
3025                    f64::from_bits(CANONICAL_F64_NAN_BITS),
3026                )),
3027            ),
3028            (
3029                Point(Point::new(1.0, 0.0_f64)),
3030                Point(Point::new(1.0, f64::from_bits(CANONICAL_F64_ZERO_BITS))),
3031            ),
3032            (
3033                Point(Point::new(1.0, -0.0_f64)),
3034                Point(Point::new(1.0, f64::from_bits(CANONICAL_F64_ZERO_BITS))),
3035            ),
3036        ];
3037
3038        for (point1, point2) in point_test_cases {
3039            assert_eq!(hash_value(&point1), hash_value(&point2));
3040        }
3041
3042        assert_eq!(hash_value(&F32(0.0)), hash_value(&F32(-0.0)));
3043        assert_eq!(hash_value(&F64(0.0)), hash_value(&F64(-0.0)));
3044        assert_eq!(
3045            hash_value(&F32(f32::NAN)),
3046            hash_value(&F32(f32::from_bits(CANONICAL_F32_NAN_BITS)))
3047        );
3048        assert_eq!(
3049            hash_value(&F64(f64::NAN)),
3050            hash_value(&F64(f64::from_bits(CANONICAL_F64_NAN_BITS)))
3051        );
3052        assert_eq!(
3053            hash_value(&F32(f32::from_bits(CANONICAL_F32_ZERO_BITS))),
3054            hash_value(&F32(0.0))
3055        );
3056        assert_eq!(
3057            hash_value(&F64(f64::from_bits(CANONICAL_F64_ZERO_BITS))),
3058            hash_value(&F64(0.0))
3059        );
3060
3061        // NaN as HashMap key
3062        let mut map = HashMap::new();
3063        map.insert(F32(f32::NAN), "test");
3064        assert_eq!(
3065            map.get(&F32(f32::from_bits(CANONICAL_F32_NAN_BITS))),
3066            Some(&"test")
3067        );
3068    }
3069
3070    #[test]
3071    fn eq() {
3072        use {
3073            super::Interval,
3074            crate::data::point::Point,
3075            chrono::{NaiveDate, NaiveTime},
3076            rust_decimal::Decimal,
3077            std::{collections::BTreeMap, net::IpAddr, str::FromStr},
3078        };
3079
3080        let test_cases = [
3081            (Bool(true), Bool(true), true),
3082            (Bool(true), Bool(false), false),
3083            (I8(42), I8(42), true),
3084            (I16(42), I16(42), true),
3085            (I32(42), I32(42), true),
3086            (I64(42), I64(42), true),
3087            (I128(42), I128(42), true),
3088            (U8(42), U8(42), true),
3089            (U16(42), U16(42), true),
3090            (U32(42), U32(42), true),
3091            (U64(42), U64(42), true),
3092            (U128(42), U128(42), true),
3093            (F32(1.5), F32(1.5), true),
3094            (F64(1.5), F64(1.5), true),
3095            (
3096                Decimal(Decimal::new(314, 2)),
3097                Decimal(Decimal::new(314, 2)),
3098                true,
3099            ),
3100            (Str("test".to_owned()), Str("test".to_owned()), true),
3101            (Bytea(vec![1, 2, 3]), Bytea(vec![1, 2, 3]), true),
3102            (
3103                Inet(IpAddr::from_str("127.0.0.1").unwrap()),
3104                Inet(IpAddr::from_str("127.0.0.1").unwrap()),
3105                true,
3106            ),
3107            (
3108                Date(NaiveDate::from_ymd_opt(2025, 1, 1).unwrap()),
3109                Date(NaiveDate::from_ymd_opt(2025, 1, 1).unwrap()),
3110                true,
3111            ),
3112            (
3113                Time(NaiveTime::from_hms_opt(10, 30, 0).unwrap()),
3114                Time(NaiveTime::from_hms_opt(10, 30, 0).unwrap()),
3115                true,
3116            ),
3117            (
3118                Interval(Interval::hours(5)),
3119                Interval(Interval::hours(5)),
3120                true,
3121            ),
3122            (Uuid(123_456_789), Uuid(123_456_789), true),
3123            (List(vec![I64(1), I64(2)]), List(vec![I64(1), I64(2)]), true),
3124            (
3125                Point(Point::new(1.0, 2.0)),
3126                Point(Point::new(1.0, 2.0)),
3127                true,
3128            ),
3129            (Null, Null, true),
3130        ];
3131
3132        for (a, b, expected) in test_cases {
3133            assert_eq!(a == b, expected);
3134        }
3135
3136        // Different types are not equal
3137        assert_ne!(Bool(true), I32(1));
3138        assert_ne!(F32(1.0), F64(1.0));
3139        assert_ne!(Null, Bool(false));
3140
3141        // Float special cases: NaN == NaN, +0.0 == -0.0
3142        assert_eq!(F32(f32::NAN), F32(f32::NAN));
3143        assert_eq!(F64(f64::NAN), F64(f64::NAN));
3144        assert_eq!(F32(0.0), F32(-0.0));
3145        assert_eq!(F64(0.0), F64(-0.0));
3146        assert_eq!(F32(f32::from_bits(0x7fc0_0001)), F32(f32::NAN));
3147
3148        assert_eq!(
3149            Point(Point::new(f64::NAN, 1.0)),
3150            Point(Point::new(f64::NAN, 1.0))
3151        );
3152        assert_eq!(
3153            Point(Point::new(1.0, f64::NAN)),
3154            Point(Point::new(1.0, f64::NAN))
3155        );
3156        assert_eq!(Point(Point::new(0.0, 1.0)), Point(Point::new(-0.0, 1.0)));
3157        assert_eq!(Point(Point::new(1.0, 0.0)), Point(Point::new(1.0, -0.0)));
3158
3159        let mut map1 = BTreeMap::new();
3160        map1.insert("a".to_owned(), I64(1));
3161        let mut map2 = BTreeMap::new();
3162        map2.insert("a".to_owned(), I64(1));
3163        assert_eq!(Map(map1), Map(map2));
3164    }
3165
3166    #[test]
3167    fn test_conversion_from_tribool() {
3168        use {super::Value, utils::Tribool};
3169
3170        assert_eq!(Value::from(Tribool::True), Value::Bool(true));
3171        assert_eq!(Value::from(Tribool::False), Value::Bool(false));
3172        assert_eq!(Value::from(Tribool::Null), Value::Null);
3173    }
3174}