toasty-core 0.3.0

Core types, schema representations, and driver interface for Toasty
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
use super::{Entry, EntryPath, Type, TypeUnion, ValueRecord, sparse_record::SparseRecord};
use std::cmp::Ordering;
use std::hash::Hash;

/// A dynamically typed value used throughout Toasty's query engine.
///
/// `Value` represents any concrete data value that flows through the query
/// pipeline: field values read from or written to the database, literal
/// constants in expressions, and intermediate results during query evaluation.
///
/// Each variant wraps a Rust type that corresponds to a [`Type`] variant.
/// Use [`Value::infer_ty`] to obtain the matching type, and [`Value::is_a`]
/// to check compatibility.
///
/// # Construction
///
/// Values are typically created via `From` conversions from Rust primitives:
///
/// ```
/// use toasty_core::stmt::Value;
///
/// let v = Value::from(42_i64);
/// assert_eq!(v, 42_i64);
///
/// let v = Value::from("hello");
/// assert_eq!(v, "hello");
///
/// let v = Value::null();
/// assert!(v.is_null());
///
/// let v = Value::from(true);
/// assert_eq!(v, true);
/// ```
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
pub enum Value {
    /// Boolean value
    Bool(bool),

    /// Signed 8-bit integer
    I8(i8),

    /// Signed 16-bit integer
    I16(i16),

    /// Signed 32-bit integer
    I32(i32),

    /// Signed 64-bit integer
    I64(i64),

    /// Unsigned 8-bit integer
    U8(u8),

    /// Unsigned 16-bit integer
    U16(u16),

    /// Unsigned 32-bit integer
    U32(u32),

    /// Unsigned 64-bit integer
    U64(u64),

    /// A typed record
    SparseRecord(SparseRecord),

    /// Null value
    #[default]
    Null,

    /// Record value, either borrowed or owned
    Record(ValueRecord),

    /// A list of values of the same type
    List(Vec<Value>),

    /// String value, either borrowed or owned
    String(String),

    /// An array of bytes that is more efficient than List(u8)
    Bytes(Vec<u8>),

    /// 128-bit universally unique identifier (UUID)
    Uuid(uuid::Uuid),

    /// A fixed-precision decimal number.
    /// See [`rust_decimal::Decimal`].
    #[cfg(feature = "rust_decimal")]
    Decimal(rust_decimal::Decimal),

    /// An arbitrary-precision decimal number.
    /// See [`bigdecimal::BigDecimal`].
    #[cfg(feature = "bigdecimal")]
    BigDecimal(bigdecimal::BigDecimal),

    /// An instant in time represented as the number of nanoseconds since the Unix epoch.
    /// See [`jiff::Timestamp`].
    #[cfg(feature = "jiff")]
    Timestamp(jiff::Timestamp),

    /// A time zone aware instant in time.
    /// See [`jiff::Zoned`]
    #[cfg(feature = "jiff")]
    Zoned(jiff::Zoned),

    /// A representation of a civil date in the Gregorian calendar.
    /// See [`jiff::civil::Date`].
    #[cfg(feature = "jiff")]
    Date(jiff::civil::Date),

    /// A representation of civil “wall clock” time.
    /// See [`jiff::civil::Time`].
    #[cfg(feature = "jiff")]
    Time(jiff::civil::Time),

    /// A representation of a civil datetime in the Gregorian calendar.
    /// See [`jiff::civil::DateTime`].
    #[cfg(feature = "jiff")]
    DateTime(jiff::civil::DateTime),
}

impl Value {
    /// Returns a null value.
    ///
    /// # Examples
    ///
    /// ```
    /// # use toasty_core::stmt::Value;
    /// let v = Value::null();
    /// assert!(v.is_null());
    /// ```
    pub const fn null() -> Self {
        Self::Null
    }

    /// Returns `true` if this value is [`Value::Null`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use toasty_core::stmt::Value;
    /// assert!(Value::Null.is_null());
    /// assert!(!Value::from(1_i64).is_null());
    /// ```
    pub const fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }

    /// Returns `true` if this value is a [`Value::Record`].
    pub const fn is_record(&self) -> bool {
        matches!(self, Self::Record(_))
    }

    /// Creates a [`Value::Record`] from a vector of field values.
    ///
    /// # Examples
    ///
    /// ```
    /// # use toasty_core::stmt::Value;
    /// let record = Value::record_from_vec(vec![Value::from(1_i64), Value::from("name")]);
    /// assert!(record.is_record());
    /// ```
    pub fn record_from_vec(fields: Vec<Self>) -> Self {
        ValueRecord::from_vec(fields).into()
    }

    /// Creates a boolean value.
    ///
    /// # Examples
    ///
    /// ```
    /// # use toasty_core::stmt::Value;
    /// let v = Value::from_bool(true);
    /// assert_eq!(v, true);
    /// ```
    pub const fn from_bool(src: bool) -> Self {
        Self::Bool(src)
    }

    /// Returns the contained string slice if this is a [`Value::String`],
    /// or `None` otherwise.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(v) => Some(&**v),
            _ => None,
        }
    }

    /// Returns the contained string slice, panicking if this is not a
    /// [`Value::String`].
    ///
    /// # Panics
    ///
    /// Panics if the value is not a `String` variant.
    pub fn as_string_unwrap(&self) -> &str {
        match self {
            Self::String(v) => v,
            _ => todo!(),
        }
    }

    /// Returns a reference to the contained [`ValueRecord`] if this is a
    /// [`Value::Record`], or `None` otherwise.
    pub fn as_record(&self) -> Option<&ValueRecord> {
        match self {
            Self::Record(record) => Some(record),
            _ => None,
        }
    }

    /// Returns a reference to the contained [`ValueRecord`], panicking if
    /// this is not a [`Value::Record`].
    ///
    /// # Panics
    ///
    /// Panics if the value is not a `Record` variant.
    pub fn as_record_unwrap(&self) -> &ValueRecord {
        match self {
            Self::Record(record) => record,
            _ => panic!("{self:#?}"),
        }
    }

    /// Returns a mutable reference to the contained [`ValueRecord`],
    /// panicking if this is not a [`Value::Record`].
    ///
    /// # Panics
    ///
    /// Panics if the value is not a `Record` variant.
    pub fn as_record_mut_unwrap(&mut self) -> &mut ValueRecord {
        match self {
            Self::Record(record) => record,
            _ => panic!(),
        }
    }

    /// Consumes this value and returns the contained [`ValueRecord`],
    /// panicking if this is not a [`Value::Record`].
    ///
    /// # Panics
    ///
    /// Panics if the value is not a `Record` variant.
    pub fn into_record(self) -> ValueRecord {
        match self {
            Self::Record(record) => record,
            _ => panic!(),
        }
    }

    /// Returns `true` if this value is compatible with the given [`Type`].
    ///
    /// Null values are compatible with any type. For union types, the value
    /// must be compatible with at least one member type.
    pub fn is_a(&self, ty: &Type) -> bool {
        if let Type::Union(types) = ty {
            return types.iter().any(|t| self.is_a(t));
        }
        match self {
            Self::Null => true,
            Self::Bool(_) => ty.is_bool(),
            Self::I8(_) => ty.is_i8(),
            Self::I16(_) => ty.is_i16(),
            Self::I32(_) => ty.is_i32(),
            Self::I64(_) => ty.is_i64(),
            Self::U8(_) => ty.is_u8(),
            Self::U16(_) => ty.is_u16(),
            Self::U32(_) => ty.is_u32(),
            Self::U64(_) => ty.is_u64(),
            Self::List(value) => match ty {
                Type::List(ty) => {
                    if value.is_empty() {
                        true
                    } else {
                        value[0].is_a(ty)
                    }
                }
                _ => false,
            },
            Self::Record(value) => match ty {
                Type::Record(fields) if value.len() == fields.len() => value
                    .fields
                    .iter()
                    .zip(fields.iter())
                    .all(|(value, ty)| value.is_a(ty)),
                _ => false,
            },
            Self::SparseRecord(value) => match ty {
                Type::SparseRecord(fields) => value.fields == *fields,
                _ => false,
            },
            Self::String(_) => ty.is_string(),
            Self::Bytes(_) => ty.is_bytes(),
            Self::Uuid(_) => ty.is_uuid(),
            #[cfg(feature = "rust_decimal")]
            Value::Decimal(_) => *ty == Type::Decimal,
            #[cfg(feature = "bigdecimal")]
            Value::BigDecimal(_) => *ty == Type::BigDecimal,
            #[cfg(feature = "jiff")]
            Value::Timestamp(_) => *ty == Type::Timestamp,
            #[cfg(feature = "jiff")]
            Value::Zoned(_) => *ty == Type::Zoned,
            #[cfg(feature = "jiff")]
            Value::Date(_) => *ty == Type::Date,
            #[cfg(feature = "jiff")]
            Value::Time(_) => *ty == Type::Time,
            #[cfg(feature = "jiff")]
            Value::DateTime(_) => *ty == Type::DateTime,
        }
    }

    /// Infers and returns the [`Type`] of this value.
    ///
    /// # Examples
    ///
    /// ```
    /// # use toasty_core::stmt::{Value, Type};
    /// assert_eq!(Value::from(42_i64).infer_ty(), Type::I64);
    /// assert_eq!(Value::from("hello").infer_ty(), Type::String);
    /// assert_eq!(Value::Null.infer_ty(), Type::Null);
    /// ```
    pub fn infer_ty(&self) -> Type {
        match self {
            Value::Bool(_) => Type::Bool,
            Value::I8(_) => Type::I8,
            Value::I16(_) => Type::I16,
            Value::I32(_) => Type::I32,
            Value::I64(_) => Type::I64,
            Value::SparseRecord(v) => Type::SparseRecord(v.fields.clone()),
            Value::Null => Type::Null,
            Value::Record(v) => Type::Record(v.fields.iter().map(Self::infer_ty).collect()),
            Value::String(_) => Type::String,
            Value::List(items) if items.is_empty() => Type::list(Type::Null),
            Value::List(items) => {
                let mut union = TypeUnion::new();
                for item in items {
                    union.insert(item.infer_ty());
                }
                Type::list(union.simplify())
            }
            Value::U8(_) => Type::U8,
            Value::U16(_) => Type::U16,
            Value::U32(_) => Type::U32,
            Value::U64(_) => Type::U64,
            Value::Bytes(_) => Type::Bytes,
            Value::Uuid(_) => Type::Uuid,
            #[cfg(feature = "rust_decimal")]
            Value::Decimal(_) => Type::Decimal,
            #[cfg(feature = "bigdecimal")]
            Value::BigDecimal(_) => Type::BigDecimal,
            #[cfg(feature = "jiff")]
            Value::Timestamp(_) => Type::Timestamp,
            #[cfg(feature = "jiff")]
            Value::Zoned(_) => Type::Zoned,
            #[cfg(feature = "jiff")]
            Value::Date(_) => Type::Date,
            #[cfg(feature = "jiff")]
            Value::Time(_) => Type::Time,
            #[cfg(feature = "jiff")]
            Value::DateTime(_) => Type::DateTime,
        }
    }

    /// Navigates into this value using the given path and returns an [`Entry`]
    /// reference to the nested value.
    ///
    /// For records, each step indexes into the record's fields. For lists,
    /// each step indexes into the list's elements.
    ///
    /// # Panics
    ///
    /// Panics if the path is invalid for the value's structure.
    #[track_caller]
    pub fn entry(&self, path: impl EntryPath) -> Entry<'_> {
        let mut ret = Entry::Value(self);

        for step in path.step_iter() {
            ret = match ret {
                Entry::Value(Self::Record(record)) => Entry::Value(&record[step]),
                Entry::Value(Self::List(items)) => Entry::Value(&items[step]),
                _ => todo!("ret={ret:#?}; base={self:#?}; step={step:#?}"),
            }
        }

        ret
    }

    /// Takes the value out, replacing it with [`Value::Null`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use toasty_core::stmt::Value;
    /// let mut v = Value::from(42_i64);
    /// let taken = v.take();
    /// assert_eq!(taken, 42_i64);
    /// assert!(v.is_null());
    /// ```
    pub fn take(&mut self) -> Self {
        std::mem::take(self)
    }
}

impl AsRef<Self> for Value {
    fn as_ref(&self) -> &Self {
        self
    }
}

impl PartialOrd for Value {
    /// Compares two values if they are of the same type.
    ///
    /// Returns `None` for:
    ///
    /// - `null` values (SQL semantics, e.g., `null` comparisons are undefined)
    /// - Comparisons across different types
    /// - Types without natural ordering (records, lists, etc.)
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (self, other) {
            // `null` comparisons are undefined.
            (Value::Null, _) | (_, Value::Null) => None,

            // Booleans.
            (Value::Bool(a), Value::Bool(b)) => a.partial_cmp(b),

            // Signed integers.
            (Value::I8(a), Value::I8(b)) => a.partial_cmp(b),
            (Value::I16(a), Value::I16(b)) => a.partial_cmp(b),
            (Value::I32(a), Value::I32(b)) => a.partial_cmp(b),
            (Value::I64(a), Value::I64(b)) => a.partial_cmp(b),

            // Unsigned integers.
            (Value::U8(a), Value::U8(b)) => a.partial_cmp(b),
            (Value::U16(a), Value::U16(b)) => a.partial_cmp(b),
            (Value::U32(a), Value::U32(b)) => a.partial_cmp(b),
            (Value::U64(a), Value::U64(b)) => a.partial_cmp(b),

            // Strings: lexicographic ordering.
            (Value::String(a), Value::String(b)) => a.partial_cmp(b),

            // Bytes: lexicographic ordering.
            (Value::Bytes(a), Value::Bytes(b)) => a.partial_cmp(b),

            // UUIDs.
            (Value::Uuid(a), Value::Uuid(b)) => a.partial_cmp(b),

            // Decimal: fixed-precision decimal numbers.
            #[cfg(feature = "rust_decimal")]
            (Value::Decimal(a), Value::Decimal(b)) => a.partial_cmp(b),

            // BigDecimal: arbitrary-precision decimal numbers.
            #[cfg(feature = "bigdecimal")]
            (Value::BigDecimal(a), Value::BigDecimal(b)) => a.partial_cmp(b),

            // Date/time types.
            #[cfg(feature = "jiff")]
            (Value::Timestamp(a), Value::Timestamp(b)) => a.partial_cmp(b),
            #[cfg(feature = "jiff")]
            (Value::Zoned(a), Value::Zoned(b)) => a.partial_cmp(b),
            #[cfg(feature = "jiff")]
            (Value::Date(a), Value::Date(b)) => a.partial_cmp(b),
            #[cfg(feature = "jiff")]
            (Value::Time(a), Value::Time(b)) => a.partial_cmp(b),
            #[cfg(feature = "jiff")]
            (Value::DateTime(a), Value::DateTime(b)) => a.partial_cmp(b),

            // Types without natural ordering or different types.
            _ => None,
        }
    }
}

impl From<bool> for Value {
    fn from(src: bool) -> Self {
        Self::Bool(src)
    }
}

impl TryFrom<Value> for bool {
    type Error = crate::Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value {
            Value::Bool(v) => Ok(v),
            _ => Err(crate::Error::type_conversion(value, "bool")),
        }
    }
}

impl From<String> for Value {
    fn from(src: String) -> Self {
        Self::String(src)
    }
}

impl From<&String> for Value {
    fn from(src: &String) -> Self {
        Self::String(src.clone())
    }
}

impl From<&str> for Value {
    fn from(src: &str) -> Self {
        Self::String(src.to_string())
    }
}

impl From<ValueRecord> for Value {
    fn from(value: ValueRecord) -> Self {
        Self::Record(value)
    }
}

impl<T> From<Option<T>> for Value
where
    Self: From<T>,
{
    fn from(value: Option<T>) -> Self {
        match value {
            Some(value) => Self::from(value),
            None => Self::Null,
        }
    }
}

impl TryFrom<Value> for String {
    type Error = crate::Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value {
            Value::String(v) => Ok(v),
            _ => Err(crate::Error::type_conversion(value, "String")),
        }
    }
}

impl From<Vec<u8>> for Value {
    fn from(value: Vec<u8>) -> Self {
        Self::Bytes(value)
    }
}

impl TryFrom<Value> for Vec<u8> {
    type Error = crate::Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value {
            Value::Bytes(v) => Ok(v),
            _ => Err(crate::Error::type_conversion(value, "Bytes")),
        }
    }
}

impl From<uuid::Uuid> for Value {
    fn from(value: uuid::Uuid) -> Self {
        Self::Uuid(value)
    }
}

impl TryFrom<Value> for uuid::Uuid {
    type Error = crate::Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value {
            Value::Uuid(v) => Ok(v),
            _ => Err(crate::Error::type_conversion(value, "uuid::Uuid")),
        }
    }
}

#[cfg(feature = "rust_decimal")]
impl From<rust_decimal::Decimal> for Value {
    fn from(value: rust_decimal::Decimal) -> Self {
        Self::Decimal(value)
    }
}

#[cfg(feature = "rust_decimal")]
impl TryFrom<Value> for rust_decimal::Decimal {
    type Error = crate::Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value {
            Value::Decimal(v) => Ok(v),
            _ => Err(crate::Error::type_conversion(
                value,
                "rust_decimal::Decimal",
            )),
        }
    }
}

#[cfg(feature = "bigdecimal")]
impl From<bigdecimal::BigDecimal> for Value {
    fn from(value: bigdecimal::BigDecimal) -> Self {
        Self::BigDecimal(value)
    }
}

#[cfg(feature = "bigdecimal")]
impl TryFrom<Value> for bigdecimal::BigDecimal {
    type Error = crate::Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value {
            Value::BigDecimal(v) => Ok(v),
            _ => Err(crate::Error::type_conversion(
                value,
                "bigdecimal::BigDecimal",
            )),
        }
    }
}