Skip to main content

icydb_core/value/
mod.rs

1mod coercion;
2mod compare;
3mod rank;
4mod tag;
5mod wire;
6
7#[cfg(test)]
8mod tests;
9
10use crate::{
11    db::StorageKey,
12    prelude::*,
13    traits::{EnumValue, FieldValue, NumFromPrimitive},
14    types::*,
15};
16use candid::CandidType;
17use serde::{Deserialize, Serialize};
18use std::cmp::Ordering;
19
20// re-exports
21pub use coercion::{CoercionFamily, CoercionFamilyExt};
22pub use tag::ValueTag;
23
24///
25/// CONSTANTS
26///
27
28const F64_SAFE_I64: i64 = 1i64 << 53;
29const F64_SAFE_U64: u64 = 1u64 << 53;
30const F64_SAFE_I128: i128 = 1i128 << 53;
31const F64_SAFE_U128: u128 = 1u128 << 53;
32
33///
34/// NumericRepr
35///
36
37enum NumericRepr {
38    Decimal(Decimal),
39    F64(f64),
40    None,
41}
42
43///
44/// TextMode
45///
46
47#[derive(Clone, Copy, Debug, Eq, PartialEq)]
48pub enum TextMode {
49    Cs, // case-sensitive
50    Ci, // case-insensitive
51}
52
53///
54/// MapValueError
55///
56/// Invariant violations for `Value::Map` construction/normalization.
57///
58
59#[derive(Clone, Debug, Eq, PartialEq)]
60pub enum MapValueError {
61    EmptyKey {
62        index: usize,
63    },
64    NonScalarKey {
65        index: usize,
66        key: Value,
67    },
68    NonScalarValue {
69        index: usize,
70        value: Value,
71    },
72    DuplicateKey {
73        left_index: usize,
74        right_index: usize,
75    },
76}
77
78impl std::fmt::Display for MapValueError {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        match self {
81            Self::EmptyKey { index } => write!(f, "map key at index {index} must be non-null"),
82            Self::NonScalarKey { index, key } => {
83                write!(f, "map key at index {index} is not scalar: {key:?}")
84            }
85            Self::NonScalarValue { index, value } => {
86                write!(
87                    f,
88                    "map value at index {index} is not scalar/ref-like: {value:?}"
89                )
90            }
91            Self::DuplicateKey {
92                left_index,
93                right_index,
94            } => write!(
95                f,
96                "map contains duplicate keys at normalized positions {left_index} and {right_index}"
97            ),
98        }
99    }
100}
101
102impl std::error::Error for MapValueError {}
103
104///
105/// SchemaInvariantError
106///
107/// Invariant violations encountered while materializing schema/runtime values.
108///
109
110#[derive(Clone, Debug, Eq, PartialEq)]
111pub enum SchemaInvariantError {
112    InvalidMapValue(MapValueError),
113}
114
115impl std::fmt::Display for SchemaInvariantError {
116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        match self {
118            Self::InvalidMapValue(err) => write!(f, "{err}"),
119        }
120    }
121}
122
123impl std::error::Error for SchemaInvariantError {}
124
125impl From<MapValueError> for SchemaInvariantError {
126    fn from(value: MapValueError) -> Self {
127        Self::InvalidMapValue(value)
128    }
129}
130
131///
132/// Value
133/// can be used in WHERE statements
134///
135/// Null        → the field’s value is Option::None (i.e., SQL NULL).
136/// Unit        → internal placeholder for RHS; not a real value.
137///
138
139#[derive(CandidType, Clone, Debug, Eq, PartialEq, Serialize)]
140pub enum Value {
141    Account(Account),
142    Blob(Vec<u8>),
143    Bool(bool),
144    Date(Date),
145    Decimal(Decimal),
146    Duration(Duration),
147    Enum(ValueEnum),
148    Float32(Float32),
149    Float64(Float64),
150    Int(i64),
151    Int128(Int128),
152    IntBig(Int),
153    /// Ordered list of values.
154    /// Used for many-cardinality transport.
155    /// List order is preserved for normalization and fingerprints.
156    List(Vec<Self>),
157    /// Canonical deterministic map representation.
158    ///
159    /// - Maps are unordered values; insertion order is discarded.
160    /// - Entries are always sorted by canonical key order and keys are unique.
161    /// - Map fields are patchable through update views, but remain non-queryable.
162    /// - Persistence treats map fields as atomic value replacements per row save.
163    Map(Vec<(Self, Self)>),
164    Null,
165    Principal(Principal),
166    Subaccount(Subaccount),
167    Text(String),
168    Timestamp(Timestamp),
169    Uint(u64),
170    Uint128(Nat128),
171    UintBig(Nat),
172    Ulid(Ulid),
173    Unit,
174}
175
176// Local helpers to expand the scalar registry into match arms.
177macro_rules! value_is_numeric_from_registry {
178    ( @args $value:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
179        match $value {
180            $( $value_pat => $is_numeric, )*
181            _ => false,
182        }
183    };
184}
185
186macro_rules! value_supports_numeric_coercion_from_registry {
187    ( @args $value:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
188        match $value {
189            $( $value_pat => $supports_numeric_coercion, )*
190            _ => false,
191        }
192    };
193}
194
195macro_rules! value_storage_key_case {
196    ( $value:expr, Unit, true ) => {
197        if let Value::Unit = $value {
198            Some(StorageKey::Unit)
199        } else {
200            None
201        }
202    };
203    ( $value:expr, $scalar:ident, true ) => {
204        if let Value::$scalar(v) = $value {
205            Some(StorageKey::$scalar(*v))
206        } else {
207            None
208        }
209    };
210    ( $value:expr, $scalar:ident, false ) => {
211        None
212    };
213}
214
215macro_rules! value_storage_key_from_registry {
216    ( @args $value:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:tt, is_storage_key_encodable = $is_storage_key_encodable:tt) ),* $(,)? ) => {
217        {
218            let mut key = None;
219            $(
220                match key {
221                    Some(_) => {}
222                    None => {
223                        key = value_storage_key_case!($value, $scalar, $is_storage_key_encodable);
224                    }
225                }
226            )*
227            key
228        }
229    };
230}
231
232macro_rules! value_coercion_family_from_registry {
233    ( @args $value:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
234        match $value {
235            $( $value_pat => $coercion_family, )*
236            Value::List(_) => CoercionFamily::Collection,
237            Value::Map(_) => CoercionFamily::Collection,
238            Value::Null => CoercionFamily::Null,
239        }
240    };
241}
242
243impl Value {
244    ///
245    /// CONSTRUCTION
246    ///
247
248    /// Build a `Value::List` from a list literal.
249    ///
250    /// Intended for tests and inline construction.
251    /// Requires `Clone` because items are borrowed.
252    pub fn from_slice<T>(items: &[T]) -> Self
253    where
254        T: Into<Self> + Clone,
255    {
256        Self::List(items.iter().cloned().map(Into::into).collect())
257    }
258
259    /// Build a `Value::List` from owned items.
260    ///
261    /// This is the canonical constructor for query / DTO boundaries.
262    pub fn from_list<T>(items: Vec<T>) -> Self
263    where
264        T: Into<Self>,
265    {
266        Self::List(items.into_iter().map(Into::into).collect())
267    }
268
269    /// Build a canonical `Value::Map` from owned key/value entries.
270    ///
271    /// Invariants are validated and entries are normalized:
272    /// - keys must be scalar and non-null
273    /// - values must be scalar/ref-like (no collections)
274    /// - entries are sorted by canonical key order
275    /// - duplicate keys are rejected
276    pub fn from_map(entries: Vec<(Self, Self)>) -> Result<Self, MapValueError> {
277        let normalized = Self::normalize_map_entries(entries)?;
278        Ok(Self::Map(normalized))
279    }
280
281    /// Validate map entry invariants without changing order.
282    pub fn validate_map_entries(entries: &[(Self, Self)]) -> Result<(), MapValueError> {
283        for (index, (key, value)) in entries.iter().enumerate() {
284            if matches!(key, Self::Null) {
285                return Err(MapValueError::EmptyKey { index });
286            }
287            if !key.is_scalar() {
288                return Err(MapValueError::NonScalarKey {
289                    index,
290                    key: key.clone(),
291                });
292            }
293
294            if !value.is_scalar() {
295                return Err(MapValueError::NonScalarValue {
296                    index,
297                    value: value.clone(),
298                });
299            }
300        }
301
302        Ok(())
303    }
304
305    /// Normalize map entries into canonical deterministic order.
306    pub fn normalize_map_entries(
307        mut entries: Vec<(Self, Self)>,
308    ) -> Result<Vec<(Self, Self)>, MapValueError> {
309        Self::validate_map_entries(&entries)?;
310        entries
311            .sort_by(|(left_key, _), (right_key, _)| Self::canonical_cmp_key(left_key, right_key));
312
313        for i in 1..entries.len() {
314            let (left_key, _) = &entries[i - 1];
315            let (right_key, _) = &entries[i];
316            if Self::canonical_cmp_key(left_key, right_key) == Ordering::Equal {
317                return Err(MapValueError::DuplicateKey {
318                    left_index: i - 1,
319                    right_index: i,
320                });
321            }
322        }
323
324        Ok(entries)
325    }
326
327    /// Build a `Value::Enum` from a domain enum using its explicit mapping.
328    pub fn from_enum<E: EnumValue>(value: E) -> Self {
329        Self::Enum(value.to_value_enum())
330    }
331
332    /// Build a strict enum value using the canonical path of `E`.
333    #[must_use]
334    pub fn enum_strict<E: Path>(variant: &str) -> Self {
335        Self::Enum(ValueEnum::strict::<E>(variant))
336    }
337
338    ///
339    /// TYPES
340    ///
341
342    /// Returns true if the value is one of the numeric-like variants
343    /// supported by numeric comparison/ordering.
344    #[must_use]
345    pub const fn is_numeric(&self) -> bool {
346        scalar_registry!(value_is_numeric_from_registry, self)
347    }
348
349    /// Returns true when numeric coercion/comparison is explicitly allowed.
350    #[must_use]
351    pub const fn supports_numeric_coercion(&self) -> bool {
352        scalar_registry!(value_supports_numeric_coercion_from_registry, self)
353    }
354
355    /// Returns true if the value is Text.
356    #[must_use]
357    pub const fn is_text(&self) -> bool {
358        matches!(self, Self::Text(_))
359    }
360
361    /// Returns true if the value is Unit (used for presence/null comparators).
362    #[must_use]
363    pub const fn is_unit(&self) -> bool {
364        matches!(self, Self::Unit)
365    }
366
367    #[must_use]
368    pub const fn is_scalar(&self) -> bool {
369        match self {
370            // definitely not scalar:
371            Self::List(_) | Self::Map(_) | Self::Unit => false,
372            _ => true,
373        }
374    }
375
376    /// Stable canonical variant tag used by hash/fingerprint encodings.
377    #[must_use]
378    pub(crate) const fn canonical_tag(&self) -> ValueTag {
379        tag::canonical_tag(self)
380    }
381
382    /// Stable canonical rank used by all cross-variant ordering surfaces.
383    #[must_use]
384    pub(crate) const fn canonical_rank(&self) -> u8 {
385        rank::canonical_rank(self)
386    }
387
388    /// Total canonical comparator used by planner/predicate/fingerprint surfaces.
389    #[must_use]
390    pub(crate) fn canonical_cmp(left: &Self, right: &Self) -> Ordering {
391        compare::canonical_cmp(left, right)
392    }
393
394    /// Total canonical comparator used for map-key normalization.
395    #[must_use]
396    pub fn canonical_cmp_key(left: &Self, right: &Self) -> Ordering {
397        compare::canonical_cmp_key(left, right)
398    }
399
400    /// Strict comparator for identical orderable variants.
401    ///
402    /// Returns `None` for mismatched or non-orderable variants.
403    #[must_use]
404    pub(crate) fn strict_order_cmp(left: &Self, right: &Self) -> Option<Ordering> {
405        compare::strict_order_cmp(left, right)
406    }
407
408    fn numeric_repr(&self) -> NumericRepr {
409        // Numeric comparison eligibility is registry-authoritative.
410        if !self.supports_numeric_coercion() {
411            return NumericRepr::None;
412        }
413
414        if let Some(d) = self.to_decimal() {
415            return NumericRepr::Decimal(d);
416        }
417        if let Some(f) = self.to_f64_lossless() {
418            return NumericRepr::F64(f);
419        }
420        NumericRepr::None
421    }
422
423    ///
424    /// CONVERSION
425    ///
426
427    /// NOTE:
428    /// `Unit` is intentionally treated as a valid storage key and indexable,
429    /// used for singleton tables and synthetic identity entities.
430    /// Only `Null` is non-indexable.
431    #[must_use]
432    pub const fn as_storage_key(&self) -> Option<StorageKey> {
433        scalar_registry!(value_storage_key_from_registry, self)
434    }
435
436    #[must_use]
437    pub const fn as_text(&self) -> Option<&str> {
438        if let Self::Text(s) = self {
439            Some(s.as_str())
440        } else {
441            None
442        }
443    }
444
445    #[must_use]
446    pub const fn as_list(&self) -> Option<&[Self]> {
447        if let Self::List(xs) = self {
448            Some(xs.as_slice())
449        } else {
450            None
451        }
452    }
453
454    #[must_use]
455    pub const fn as_map(&self) -> Option<&[(Self, Self)]> {
456        if let Self::Map(entries) = self {
457            Some(entries.as_slice())
458        } else {
459            None
460        }
461    }
462
463    fn to_decimal(&self) -> Option<Decimal> {
464        match self {
465            Self::Decimal(d) => Some(*d),
466            Self::Duration(d) => Decimal::from_u64(d.repr()),
467            Self::Float64(f) => Decimal::from_f64(f.get()),
468            Self::Float32(f) => Decimal::from_f32(f.get()),
469            Self::Int(i) => Decimal::from_i64(*i),
470            Self::Int128(i) => Decimal::from_i128(i.get()),
471            Self::IntBig(i) => i.to_i128().and_then(Decimal::from_i128),
472            Self::Timestamp(t) => Decimal::from_u64(t.repr()),
473            Self::Uint(u) => Decimal::from_u64(*u),
474            Self::Uint128(u) => Decimal::from_u128(u.get()),
475            Self::UintBig(u) => u.to_u128().and_then(Decimal::from_u128),
476
477            _ => None,
478        }
479    }
480
481    // Internal numeric coercion helper for aggregate arithmetic.
482    pub(crate) fn to_numeric_decimal(&self) -> Option<Decimal> {
483        self.to_decimal()
484    }
485
486    // it's lossless, trust me bro
487    #[expect(clippy::cast_precision_loss)]
488    fn to_f64_lossless(&self) -> Option<f64> {
489        match self {
490            Self::Duration(d) if d.repr() <= F64_SAFE_U64 => Some(d.repr() as f64),
491            Self::Float64(f) => Some(f.get()),
492            Self::Float32(f) => Some(f64::from(f.get())),
493            Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
494            Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
495                Some(i.get() as f64)
496            }
497            Self::IntBig(i) => i.to_i128().and_then(|v| {
498                (-F64_SAFE_I128..=F64_SAFE_I128)
499                    .contains(&v)
500                    .then_some(v as f64)
501            }),
502            Self::Timestamp(t) if t.repr() <= F64_SAFE_U64 => Some(t.repr() as f64),
503            Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
504            Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
505            Self::UintBig(u) => u
506                .to_u128()
507                .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
508
509            _ => None,
510        }
511    }
512
513    /// Cross-type numeric comparison; returns None if non-numeric.
514    #[must_use]
515    pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
516        if !self.supports_numeric_coercion() || !other.supports_numeric_coercion() {
517            return None;
518        }
519
520        match (self.numeric_repr(), other.numeric_repr()) {
521            (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
522            (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
523            _ => None,
524        }
525    }
526
527    ///
528    /// TEXT COMPARISON
529    ///
530
531    fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
532        if s.is_ascii() {
533            return std::borrow::Cow::Owned(s.to_ascii_lowercase());
534        }
535        // NOTE: Unicode fallback — temporary to_lowercase for non‑ASCII.
536        // Future: replace with proper NFKC + full casefold when available.
537        std::borrow::Cow::Owned(s.to_lowercase())
538    }
539
540    fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
541        match mode {
542            TextMode::Cs => std::borrow::Cow::Borrowed(s),
543            TextMode::Ci => Self::fold_ci(s),
544        }
545    }
546
547    fn text_op(
548        &self,
549        other: &Self,
550        mode: TextMode,
551        f: impl Fn(&str, &str) -> bool,
552    ) -> Option<bool> {
553        let (a, b) = (self.as_text()?, other.as_text()?);
554        let a = Self::text_with_mode(a, mode);
555        let b = Self::text_with_mode(b, mode);
556        Some(f(&a, &b))
557    }
558
559    fn ci_key(&self) -> Option<String> {
560        match self {
561            Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
562            Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
563            Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
564            Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
565            _ => None,
566        }
567    }
568
569    fn eq_ci(a: &Self, b: &Self) -> bool {
570        if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
571            return ak == bk;
572        }
573
574        a == b
575    }
576
577    fn normalize_list_ref(v: &Self) -> Vec<&Self> {
578        match v {
579            Self::List(vs) => vs.iter().collect(),
580            v => vec![v],
581        }
582    }
583
584    fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
585    where
586        F: Fn(&Self, &Self) -> bool,
587    {
588        self.as_list()
589            .map(|items| items.iter().any(|v| eq(v, needle)))
590    }
591
592    #[expect(clippy::unnecessary_wraps)]
593    fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
594    where
595        F: Fn(&Self, &Self) -> bool,
596    {
597        let needles = Self::normalize_list_ref(needles);
598        match self {
599            Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
600            scalar => Some(needles.iter().any(|n| eq(scalar, n))),
601        }
602    }
603
604    #[expect(clippy::unnecessary_wraps)]
605    fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
606    where
607        F: Fn(&Self, &Self) -> bool,
608    {
609        let needles = Self::normalize_list_ref(needles);
610        match self {
611            Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
612            scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
613        }
614    }
615
616    fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
617    where
618        F: Fn(&Self, &Self) -> bool,
619    {
620        if let Self::List(items) = haystack {
621            Some(items.iter().any(|h| eq(h, self)))
622        } else {
623            None
624        }
625    }
626
627    #[must_use]
628    /// Case-sensitive/insensitive equality check for text-like values.
629    pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
630        self.text_op(other, mode, |a, b| a == b)
631    }
632
633    #[must_use]
634    /// Check whether `other` is a substring of `self` under the given text mode.
635    pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
636        self.text_op(needle, mode, |a, b| a.contains(b))
637    }
638
639    #[must_use]
640    /// Check whether `self` starts with `other` under the given text mode.
641    pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
642        self.text_op(needle, mode, |a, b| a.starts_with(b))
643    }
644
645    #[must_use]
646    /// Check whether `self` ends with `other` under the given text mode.
647    pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
648        self.text_op(needle, mode, |a, b| a.ends_with(b))
649    }
650
651    ///
652    /// EMPTY
653    ///
654
655    #[must_use]
656    pub const fn is_empty(&self) -> Option<bool> {
657        match self {
658            Self::List(xs) => Some(xs.is_empty()),
659            Self::Map(entries) => Some(entries.is_empty()),
660            Self::Text(s) => Some(s.is_empty()),
661            Self::Blob(b) => Some(b.is_empty()),
662
663            //  fields represented as Value::Null:
664            Self::Null => Some(true),
665
666            _ => None,
667        }
668    }
669
670    #[must_use]
671    /// Logical negation of [`is_empty`](Self::is_empty).
672    pub fn is_not_empty(&self) -> Option<bool> {
673        self.is_empty().map(|b| !b)
674    }
675
676    ///
677    /// COLLECTIONS
678    ///
679
680    #[must_use]
681    /// Returns true if `self` contains `needle` (or equals it for scalars).
682    pub fn contains(&self, needle: &Self) -> Option<bool> {
683        self.contains_by(needle, |a, b| a == b)
684    }
685
686    #[must_use]
687    /// Returns true if any item in `needles` matches a member of `self`.
688    pub fn contains_any(&self, needles: &Self) -> Option<bool> {
689        self.contains_any_by(needles, |a, b| a == b)
690    }
691
692    #[must_use]
693    /// Returns true if every item in `needles` matches a member of `self`.
694    pub fn contains_all(&self, needles: &Self) -> Option<bool> {
695        self.contains_all_by(needles, |a, b| a == b)
696    }
697
698    #[must_use]
699    /// Returns true if `self` exists inside the provided list.
700    pub fn in_list(&self, haystack: &Self) -> Option<bool> {
701        self.in_list_by(haystack, |a, b| a == b)
702    }
703
704    #[must_use]
705    /// Case-insensitive `contains` supporting text and identifier variants.
706    pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
707        match self {
708            Self::List(_) => self.contains_by(needle, Self::eq_ci),
709            _ => Some(Self::eq_ci(self, needle)),
710        }
711    }
712
713    #[must_use]
714    /// Case-insensitive variant of [`contains_any`](Self::contains_any).
715    pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
716        self.contains_any_by(needles, Self::eq_ci)
717    }
718
719    #[must_use]
720    /// Case-insensitive variant of [`contains_all`](Self::contains_all).
721    pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
722        self.contains_all_by(needles, Self::eq_ci)
723    }
724
725    #[must_use]
726    /// Case-insensitive variant of [`in_list`](Self::in_list).
727    pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
728        self.in_list_by(haystack, Self::eq_ci)
729    }
730}
731
732impl FieldValue for Value {
733    fn kind() -> crate::traits::FieldValueKind {
734        crate::traits::FieldValueKind::Atomic
735    }
736
737    fn to_value(&self) -> Value {
738        self.clone()
739    }
740
741    fn from_value(value: &Value) -> Option<Self> {
742        Some(value.clone())
743    }
744}
745
746#[macro_export]
747macro_rules! impl_from_for {
748    ( $( $type:ty => $variant:ident ),* $(,)? ) => {
749        $(
750            impl From<$type> for Value {
751                fn from(v: $type) -> Self {
752                    Self::$variant(v.into())
753                }
754            }
755        )*
756    };
757}
758
759impl_from_for! {
760    Account    => Account,
761    Date       => Date,
762    Decimal    => Decimal,
763    Duration   => Duration,
764    bool       => Bool,
765    i8         => Int,
766    i16        => Int,
767    i32        => Int,
768    i64        => Int,
769    i128       => Int128,
770    Int        => IntBig,
771    Principal  => Principal,
772    Subaccount => Subaccount,
773    &str       => Text,
774    String     => Text,
775    Timestamp  => Timestamp,
776    u8         => Uint,
777    u16        => Uint,
778    u32        => Uint,
779    u64        => Uint,
780    u128       => Uint128,
781    Nat        => UintBig,
782    Ulid       => Ulid,
783}
784
785impl CoercionFamilyExt for Value {
786    /// Returns the coercion-routing family for this value.
787    ///
788    /// NOTE:
789    /// This does NOT imply numeric, arithmetic, ordering, or keyability support.
790    /// All scalar capabilities are registry-driven.
791    fn coercion_family(&self) -> CoercionFamily {
792        scalar_registry!(value_coercion_family_from_registry, self)
793    }
794}
795
796impl From<Vec<Self>> for Value {
797    fn from(vec: Vec<Self>) -> Self {
798        Self::List(vec)
799    }
800}
801
802impl TryFrom<Vec<(Self, Self)>> for Value {
803    type Error = SchemaInvariantError;
804
805    fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
806        Self::from_map(entries).map_err(Self::Error::from)
807    }
808}
809
810impl From<()> for Value {
811    fn from((): ()) -> Self {
812        Self::Unit
813    }
814}
815
816// NOTE:
817// Value::partial_cmp is NOT the canonical ordering for database semantics.
818// Some orderable scalar types (e.g. Account, Unit) intentionally do not
819// participate here. Use canonical_cmp / strict ordering for ORDER BY,
820// planning, and key-range validation.
821impl PartialOrd for Value {
822    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
823        match (self, other) {
824            (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
825            (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
826            (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
827            (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
828            (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
829            (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
830            (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
831            (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
832            (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
833            (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
834            (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
835            (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
836            (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
837            (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
838            (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
839            (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
840            (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
841            (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
842            (Self::Map(a), Self::Map(b)) => {
843                for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
844                    let key_cmp = Self::canonical_cmp_key(left_key, right_key);
845                    if key_cmp != Ordering::Equal {
846                        return Some(key_cmp);
847                    }
848
849                    match left_value.partial_cmp(right_value) {
850                        Some(Ordering::Equal) => {}
851                        non_eq => return non_eq,
852                    }
853                }
854                a.len().partial_cmp(&b.len())
855            }
856
857            // Cross-type comparisons: no ordering
858            _ => None,
859        }
860    }
861}
862
863///
864/// ValueEnum
865/// handles the Enum case; `path` is optional to allow strict (typed) or loose matching.
866///
867
868#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
869pub struct ValueEnum {
870    pub variant: String,
871    pub path: Option<String>,
872    pub payload: Option<Box<Value>>,
873}
874
875impl ValueEnum {
876    #[must_use]
877    /// Build a strict enum value matching the provided variant and path.
878    pub fn new(variant: &str, path: Option<&str>) -> Self {
879        Self {
880            variant: variant.to_string(),
881            path: path.map(ToString::to_string),
882            payload: None,
883        }
884    }
885
886    #[must_use]
887    /// Build a strict enum value using the canonical path of `E`.
888    pub fn strict<E: Path>(variant: &str) -> Self {
889        Self::new(variant, Some(E::PATH))
890    }
891
892    #[must_use]
893    /// Build a strict enum value from a domain enum using its explicit mapping.
894    pub fn from_enum<E: EnumValue>(value: E) -> Self {
895        value.to_value_enum()
896    }
897
898    #[must_use]
899    /// Build an enum value with an unresolved path for filter construction.
900    /// Query normalization resolves this to the schema enum path before validation.
901    pub fn loose(variant: &str) -> Self {
902        Self::new(variant, None)
903    }
904
905    #[must_use]
906    /// Attach an enum payload (used for data-carrying variants).
907    pub fn with_payload(mut self, payload: Value) -> Self {
908        self.payload = Some(Box::new(payload));
909        self
910    }
911}