1#![allow(clippy::derive_ord_xor_partial_ord)]
2
3use crate::ctx::Context;
4use crate::dbs::Options;
5use crate::doc::CursorDoc;
6use crate::err::Error;
7use crate::fnc::util::string::fuzzy::Fuzzy;
8use crate::sql::id::range::IdRange;
9use crate::sql::kind::Literal;
10use crate::sql::range::OldRange;
11use crate::sql::reference::Refs;
12use crate::sql::statements::info::InfoStructure;
13use crate::sql::Closure;
14use crate::sql::{
15 array::Uniq,
16 fmt::{Fmt, Pretty},
17 id::{Gen, Id},
18 model::Model,
19 Array, Block, Bytes, Cast, Constant, Datetime, Duration, Edges, Expression, Function, Future,
20 Geometry, Idiom, Kind, Mock, Number, Object, Operation, Param, Part, Query, Range, Regex,
21 Strand, Subquery, Table, Tables, Thing, Uuid,
22};
23use chrono::{DateTime, Utc};
24
25use geo::Point;
26use reblessive::tree::Stk;
27use revision::revisioned;
28use rust_decimal::prelude::*;
29use serde::{Deserialize, Serialize};
30use serde_json::Value as Json;
31use std::cmp::Ordering;
32use std::collections::BTreeMap;
33use std::collections::HashMap;
34use std::fmt::{self, Display, Formatter, Write};
35use std::ops::{Bound, Deref};
36
37pub(crate) const TOKEN: &str = "$surrealdb::private::sql::Value";
38
39#[revisioned(revision = 1)]
40#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Hash)]
41#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
42#[non_exhaustive]
43pub struct Values(pub Vec<Value>);
44
45impl<V> From<V> for Values
46where
47 V: Into<Vec<Value>>,
48{
49 fn from(value: V) -> Self {
50 Self(value.into())
51 }
52}
53
54impl Deref for Values {
55 type Target = Vec<Value>;
56 fn deref(&self) -> &Self::Target {
57 &self.0
58 }
59}
60
61impl IntoIterator for Values {
62 type Item = Value;
63 type IntoIter = std::vec::IntoIter<Self::Item>;
64 fn into_iter(self) -> Self::IntoIter {
65 self.0.into_iter()
66 }
67}
68
69impl Display for Values {
70 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
71 Display::fmt(&Fmt::comma_separated(&self.0), f)
72 }
73}
74
75impl InfoStructure for Values {
76 fn structure(self) -> Value {
77 self.into_iter().map(Value::structure).collect::<Vec<_>>().into()
78 }
79}
80
81impl From<&Tables> for Values {
82 fn from(tables: &Tables) -> Self {
83 Self(tables.0.iter().map(|t| Value::Table(t.clone())).collect())
84 }
85}
86
87#[revisioned(revision = 2)]
88#[derive(Clone, Debug, Default, PartialEq, PartialOrd, Serialize, Deserialize, Hash)]
89#[serde(rename = "$surrealdb::private::sql::Value")]
90#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
91#[non_exhaustive]
92pub enum Value {
93 #[default]
101 None,
102 Null,
103 Bool(bool),
104 Number(Number),
105 Strand(Strand),
106 Duration(Duration),
107 Datetime(Datetime),
108 Uuid(Uuid),
109 Array(Array),
110 Object(Object),
111 Geometry(Geometry),
112 Bytes(Bytes),
113 Thing(Thing),
114 Param(Param),
122 Idiom(Idiom),
123 Table(Table),
124 Mock(Mock),
125 Regex(Regex),
126 Cast(Box<Cast>),
127 Block(Box<Block>),
128 #[revision(end = 2, convert_fn = "convert_old_range", fields_name = "OldValueRangeFields")]
129 Range(OldRange),
130 #[revision(start = 2)]
131 Range(Box<Range>),
132 Edges(Box<Edges>),
133 Future(Box<Future>),
134 Constant(Constant),
135 Function(Box<Function>),
136 Subquery(Box<Subquery>),
137 Expression(Box<Expression>),
138 Query(Query),
139 Model(Box<Model>),
140 Closure(Box<Closure>),
141 Refs(Refs),
142 }
144
145impl Value {
146 fn convert_old_range(
147 fields: OldValueRangeFields,
148 _revision: u16,
149 ) -> Result<Self, revision::Error> {
150 Ok(Value::Thing(Thing {
151 tb: fields.0.tb,
152 id: Id::Range(Box::new(IdRange {
153 beg: fields.0.beg,
154 end: fields.0.end,
155 })),
156 }))
157 }
158}
159
160impl Eq for Value {}
161
162impl Ord for Value {
163 fn cmp(&self, other: &Self) -> Ordering {
164 self.partial_cmp(other).unwrap_or(Ordering::Equal)
165 }
166}
167
168impl From<bool> for Value {
169 #[inline]
170 fn from(v: bool) -> Self {
171 Value::Bool(v)
172 }
173}
174
175impl From<Uuid> for Value {
176 fn from(v: Uuid) -> Self {
177 Value::Uuid(v)
178 }
179}
180
181impl From<Closure> for Value {
182 fn from(v: Closure) -> Self {
183 Value::Closure(Box::new(v))
184 }
185}
186
187impl From<Param> for Value {
188 fn from(v: Param) -> Self {
189 Value::Param(v)
190 }
191}
192
193impl From<Idiom> for Value {
194 fn from(v: Idiom) -> Self {
195 Value::Idiom(v)
196 }
197}
198
199impl From<Mock> for Value {
200 fn from(v: Mock) -> Self {
201 Value::Mock(v)
202 }
203}
204
205impl From<Table> for Value {
206 fn from(v: Table) -> Self {
207 Value::Table(v)
208 }
209}
210
211impl From<Thing> for Value {
212 fn from(v: Thing) -> Self {
213 Value::Thing(v)
214 }
215}
216
217impl From<Regex> for Value {
218 fn from(v: Regex) -> Self {
219 Value::Regex(v)
220 }
221}
222
223impl From<Bytes> for Value {
224 fn from(v: Bytes) -> Self {
225 Value::Bytes(v)
226 }
227}
228
229impl From<Array> for Value {
230 fn from(v: Array) -> Self {
231 Value::Array(v)
232 }
233}
234
235impl From<Object> for Value {
236 fn from(v: Object) -> Self {
237 Value::Object(v)
238 }
239}
240
241impl From<Number> for Value {
242 fn from(v: Number) -> Self {
243 Value::Number(v)
244 }
245}
246
247impl From<Strand> for Value {
248 fn from(v: Strand) -> Self {
249 Value::Strand(v)
250 }
251}
252
253impl From<Geometry> for Value {
254 fn from(v: Geometry) -> Self {
255 Value::Geometry(v)
256 }
257}
258
259impl From<Datetime> for Value {
260 fn from(v: Datetime) -> Self {
261 Value::Datetime(v)
262 }
263}
264
265impl From<Duration> for Value {
266 fn from(v: Duration) -> Self {
267 Value::Duration(v)
268 }
269}
270
271impl From<Constant> for Value {
272 fn from(v: Constant) -> Self {
273 Value::Constant(v)
274 }
275}
276
277impl From<Block> for Value {
278 fn from(v: Block) -> Self {
279 Value::Block(Box::new(v))
280 }
281}
282
283impl From<Range> for Value {
284 fn from(v: Range) -> Self {
285 Value::Range(Box::new(v))
286 }
287}
288
289impl From<Box<Range>> for Value {
290 fn from(v: Box<Range>) -> Self {
291 Value::Range(v)
292 }
293}
294
295impl From<Edges> for Value {
296 fn from(v: Edges) -> Self {
297 Value::Edges(Box::new(v))
298 }
299}
300
301impl From<Future> for Value {
302 fn from(v: Future) -> Self {
303 Value::Future(Box::new(v))
304 }
305}
306
307impl From<Cast> for Value {
308 fn from(v: Cast) -> Self {
309 Value::Cast(Box::new(v))
310 }
311}
312
313impl From<Function> for Value {
314 fn from(v: Function) -> Self {
315 Value::Function(Box::new(v))
316 }
317}
318
319impl From<Model> for Value {
320 fn from(v: Model) -> Self {
321 Value::Model(Box::new(v))
322 }
323}
324
325impl From<Subquery> for Value {
326 fn from(v: Subquery) -> Self {
327 Value::Subquery(Box::new(v))
328 }
329}
330
331impl From<Expression> for Value {
332 fn from(v: Expression) -> Self {
333 Value::Expression(Box::new(v))
334 }
335}
336
337impl From<Box<Edges>> for Value {
338 fn from(v: Box<Edges>) -> Self {
339 Value::Edges(v)
340 }
341}
342
343impl From<i8> for Value {
344 fn from(v: i8) -> Self {
345 Value::Number(Number::from(v))
346 }
347}
348
349impl From<i16> for Value {
350 fn from(v: i16) -> Self {
351 Value::Number(Number::from(v))
352 }
353}
354
355impl From<i32> for Value {
356 fn from(v: i32) -> Self {
357 Value::Number(Number::from(v))
358 }
359}
360
361impl From<i64> for Value {
362 fn from(v: i64) -> Self {
363 Value::Number(Number::from(v))
364 }
365}
366
367impl From<i128> for Value {
368 fn from(v: i128) -> Self {
369 Value::Number(Number::from(v))
370 }
371}
372
373impl From<isize> for Value {
374 fn from(v: isize) -> Self {
375 Value::Number(Number::from(v))
376 }
377}
378
379impl From<u8> for Value {
380 fn from(v: u8) -> Self {
381 Value::Number(Number::from(v))
382 }
383}
384
385impl From<u16> for Value {
386 fn from(v: u16) -> Self {
387 Value::Number(Number::from(v))
388 }
389}
390
391impl From<u32> for Value {
392 fn from(v: u32) -> Self {
393 Value::Number(Number::from(v))
394 }
395}
396
397impl From<u64> for Value {
398 fn from(v: u64) -> Self {
399 Value::Number(Number::from(v))
400 }
401}
402
403impl From<u128> for Value {
404 fn from(v: u128) -> Self {
405 Value::Number(Number::from(v))
406 }
407}
408
409impl From<usize> for Value {
410 fn from(v: usize) -> Self {
411 Value::Number(Number::from(v))
412 }
413}
414
415impl From<f32> for Value {
416 fn from(v: f32) -> Self {
417 Value::Number(Number::from(v))
418 }
419}
420
421impl From<f64> for Value {
422 fn from(v: f64) -> Self {
423 Value::Number(Number::from(v))
424 }
425}
426
427impl From<Decimal> for Value {
428 fn from(v: Decimal) -> Self {
429 Value::Number(Number::from(v))
430 }
431}
432
433impl From<String> for Value {
434 fn from(v: String) -> Self {
435 Self::Strand(Strand::from(v))
436 }
437}
438
439impl From<&str> for Value {
440 fn from(v: &str) -> Self {
441 Self::Strand(Strand::from(v))
442 }
443}
444
445impl From<DateTime<Utc>> for Value {
446 fn from(v: DateTime<Utc>) -> Self {
447 Value::Datetime(Datetime::from(v))
448 }
449}
450
451impl From<(f64, f64)> for Value {
452 fn from(v: (f64, f64)) -> Self {
453 Value::Geometry(Geometry::from(v))
454 }
455}
456
457impl From<[f64; 2]> for Value {
458 fn from(v: [f64; 2]) -> Self {
459 Value::Geometry(Geometry::from(v))
460 }
461}
462
463impl From<Point<f64>> for Value {
464 fn from(v: Point<f64>) -> Self {
465 Value::Geometry(Geometry::from(v))
466 }
467}
468
469impl From<Operation> for Value {
470 fn from(v: Operation) -> Self {
471 Value::Object(Object::from(v))
472 }
473}
474
475impl From<uuid::Uuid> for Value {
476 fn from(v: uuid::Uuid) -> Self {
477 Value::Uuid(Uuid(v))
478 }
479}
480
481impl From<Vec<&str>> for Value {
482 fn from(v: Vec<&str>) -> Self {
483 Value::Array(Array::from(v))
484 }
485}
486
487impl From<Vec<String>> for Value {
488 fn from(v: Vec<String>) -> Self {
489 Value::Array(Array::from(v))
490 }
491}
492
493impl From<Vec<i32>> for Value {
494 fn from(v: Vec<i32>) -> Self {
495 Value::Array(Array::from(v))
496 }
497}
498
499impl From<Vec<f32>> for Value {
500 fn from(v: Vec<f32>) -> Self {
501 Value::Array(Array::from(v))
502 }
503}
504
505impl From<Vec<f64>> for Value {
506 fn from(v: Vec<f64>) -> Self {
507 Value::Array(Array::from(v))
508 }
509}
510
511impl From<Vec<usize>> for Value {
512 fn from(v: Vec<usize>) -> Self {
513 Value::Array(Array::from(v))
514 }
515}
516
517impl From<Vec<Value>> for Value {
518 fn from(v: Vec<Value>) -> Self {
519 Value::Array(Array::from(v))
520 }
521}
522
523impl From<Vec<Number>> for Value {
524 fn from(v: Vec<Number>) -> Self {
525 Value::Array(Array::from(v))
526 }
527}
528
529impl From<Vec<Operation>> for Value {
530 fn from(v: Vec<Operation>) -> Self {
531 Value::Array(Array::from(v))
532 }
533}
534
535impl From<Vec<bool>> for Value {
536 fn from(v: Vec<bool>) -> Self {
537 Value::Array(Array::from(v))
538 }
539}
540
541impl From<HashMap<&str, Value>> for Value {
542 fn from(v: HashMap<&str, Value>) -> Self {
543 Value::Object(Object::from(v))
544 }
545}
546
547impl From<HashMap<String, Value>> for Value {
548 fn from(v: HashMap<String, Value>) -> Self {
549 Value::Object(Object::from(v))
550 }
551}
552
553impl From<BTreeMap<String, Value>> for Value {
554 fn from(v: BTreeMap<String, Value>) -> Self {
555 Value::Object(Object::from(v))
556 }
557}
558
559impl From<BTreeMap<&str, Value>> for Value {
560 fn from(v: BTreeMap<&str, Value>) -> Self {
561 Value::Object(Object::from(v))
562 }
563}
564
565impl From<Option<Value>> for Value {
566 fn from(v: Option<Value>) -> Self {
567 match v {
568 Some(v) => v,
569 None => Value::None,
570 }
571 }
572}
573
574impl From<Option<String>> for Value {
575 fn from(v: Option<String>) -> Self {
576 match v {
577 Some(v) => Value::from(v),
578 None => Value::None,
579 }
580 }
581}
582
583impl From<Option<i64>> for Value {
584 fn from(v: Option<i64>) -> Self {
585 match v {
586 Some(v) => Value::from(v),
587 None => Value::None,
588 }
589 }
590}
591
592impl From<Option<Duration>> for Value {
593 fn from(v: Option<Duration>) -> Self {
594 match v {
595 Some(v) => Value::from(v),
596 None => Value::None,
597 }
598 }
599}
600
601impl From<Option<Datetime>> for Value {
602 fn from(v: Option<Datetime>) -> Self {
603 match v {
604 Some(v) => Value::from(v),
605 None => Value::None,
606 }
607 }
608}
609
610impl From<IdRange> for Value {
611 fn from(v: IdRange) -> Self {
612 let beg = match v.beg {
613 Bound::Included(beg) => Bound::Included(Value::from(beg)),
614 Bound::Excluded(beg) => Bound::Excluded(Value::from(beg)),
615 Bound::Unbounded => Bound::Unbounded,
616 };
617
618 let end = match v.end {
619 Bound::Included(end) => Bound::Included(Value::from(end)),
620 Bound::Excluded(end) => Bound::Excluded(Value::from(end)),
621 Bound::Unbounded => Bound::Unbounded,
622 };
623
624 Value::Range(Box::new(Range {
625 beg,
626 end,
627 }))
628 }
629}
630
631impl From<Id> for Value {
632 fn from(v: Id) -> Self {
633 match v {
634 Id::Number(v) => v.into(),
635 Id::String(v) => v.into(),
636 Id::Uuid(v) => v.into(),
637 Id::Array(v) => v.into(),
638 Id::Object(v) => v.into(),
639 Id::Generate(v) => match v {
640 Gen::Rand => Id::rand().into(),
641 Gen::Ulid => Id::ulid().into(),
642 Gen::Uuid => Id::uuid().into(),
643 },
644 Id::Range(v) => v.deref().to_owned().into(),
645 }
646 }
647}
648
649impl From<Query> for Value {
650 fn from(q: Query) -> Self {
651 Value::Query(q)
652 }
653}
654
655impl TryFrom<Value> for i8 {
656 type Error = Error;
657 fn try_from(value: Value) -> Result<Self, Self::Error> {
658 match value {
659 Value::Number(x) => x.try_into(),
660 _ => Err(Error::TryFrom(value.to_string(), "i8")),
661 }
662 }
663}
664
665impl TryFrom<Value> for i16 {
666 type Error = Error;
667 fn try_from(value: Value) -> Result<Self, Self::Error> {
668 match value {
669 Value::Number(x) => x.try_into(),
670 _ => Err(Error::TryFrom(value.to_string(), "i16")),
671 }
672 }
673}
674
675impl TryFrom<Value> for i32 {
676 type Error = Error;
677 fn try_from(value: Value) -> Result<Self, Self::Error> {
678 match value {
679 Value::Number(x) => x.try_into(),
680 _ => Err(Error::TryFrom(value.to_string(), "i32")),
681 }
682 }
683}
684
685impl TryFrom<Value> for i64 {
686 type Error = Error;
687 fn try_from(value: Value) -> Result<Self, Self::Error> {
688 match value {
689 Value::Number(x) => x.try_into(),
690 _ => Err(Error::TryFrom(value.to_string(), "i64")),
691 }
692 }
693}
694
695impl TryFrom<Value> for i128 {
696 type Error = Error;
697 fn try_from(value: Value) -> Result<Self, Self::Error> {
698 match value {
699 Value::Number(x) => x.try_into(),
700 _ => Err(Error::TryFrom(value.to_string(), "i128")),
701 }
702 }
703}
704
705impl TryFrom<Value> for u8 {
706 type Error = Error;
707 fn try_from(value: Value) -> Result<Self, Self::Error> {
708 match value {
709 Value::Number(x) => x.try_into(),
710 _ => Err(Error::TryFrom(value.to_string(), "u8")),
711 }
712 }
713}
714
715impl TryFrom<Value> for u16 {
716 type Error = Error;
717 fn try_from(value: Value) -> Result<Self, Self::Error> {
718 match value {
719 Value::Number(x) => x.try_into(),
720 _ => Err(Error::TryFrom(value.to_string(), "u16")),
721 }
722 }
723}
724
725impl TryFrom<Value> for u32 {
726 type Error = Error;
727 fn try_from(value: Value) -> Result<Self, Self::Error> {
728 match value {
729 Value::Number(x) => x.try_into(),
730 _ => Err(Error::TryFrom(value.to_string(), "u32")),
731 }
732 }
733}
734
735impl TryFrom<Value> for u64 {
736 type Error = Error;
737 fn try_from(value: Value) -> Result<Self, Self::Error> {
738 match value {
739 Value::Number(x) => x.try_into(),
740 _ => Err(Error::TryFrom(value.to_string(), "u64")),
741 }
742 }
743}
744
745impl TryFrom<Value> for u128 {
746 type Error = Error;
747 fn try_from(value: Value) -> Result<Self, Self::Error> {
748 match value {
749 Value::Number(x) => x.try_into(),
750 _ => Err(Error::TryFrom(value.to_string(), "u128")),
751 }
752 }
753}
754
755impl TryFrom<Value> for f32 {
756 type Error = Error;
757 fn try_from(value: Value) -> Result<Self, Self::Error> {
758 match value {
759 Value::Number(x) => x.try_into(),
760 _ => Err(Error::TryFrom(value.to_string(), "f32")),
761 }
762 }
763}
764
765impl TryFrom<Value> for f64 {
766 type Error = Error;
767 fn try_from(value: Value) -> Result<Self, Self::Error> {
768 match value {
769 Value::Number(x) => x.try_into(),
770 _ => Err(Error::TryFrom(value.to_string(), "f64")),
771 }
772 }
773}
774
775impl TryFrom<Value> for Decimal {
776 type Error = Error;
777 fn try_from(value: Value) -> Result<Self, Self::Error> {
778 match value {
779 Value::Number(x) => x.try_into(),
780 _ => Err(Error::TryFrom(value.to_string(), "Decimal")),
781 }
782 }
783}
784
785impl TryFrom<Value> for String {
786 type Error = Error;
787 fn try_from(value: Value) -> Result<Self, Self::Error> {
788 match value {
789 Value::Strand(x) => Ok(x.into()),
790 _ => Err(Error::TryFrom(value.to_string(), "String")),
791 }
792 }
793}
794
795impl TryFrom<Value> for bool {
796 type Error = Error;
797 fn try_from(value: Value) -> Result<Self, Self::Error> {
798 match value {
799 Value::Bool(v) => Ok(v),
800 _ => Err(Error::TryFrom(value.to_string(), "bool")),
801 }
802 }
803}
804
805impl TryFrom<Value> for std::time::Duration {
806 type Error = Error;
807 fn try_from(value: Value) -> Result<Self, Self::Error> {
808 match value {
809 Value::Duration(x) => Ok(x.into()),
810 _ => Err(Error::TryFrom(value.to_string(), "time::Duration")),
811 }
812 }
813}
814
815impl TryFrom<Value> for DateTime<Utc> {
816 type Error = Error;
817 fn try_from(value: Value) -> Result<Self, Self::Error> {
818 match value {
819 Value::Datetime(x) => Ok(x.into()),
820 _ => Err(Error::TryFrom(value.to_string(), "chrono::DateTime<Utc>")),
821 }
822 }
823}
824
825impl TryFrom<Value> for uuid::Uuid {
826 type Error = Error;
827 fn try_from(value: Value) -> Result<Self, Self::Error> {
828 match value {
829 Value::Uuid(x) => Ok(x.into()),
830 _ => Err(Error::TryFrom(value.to_string(), "uuid::Uuid")),
831 }
832 }
833}
834
835impl TryFrom<Value> for Vec<Value> {
836 type Error = Error;
837 fn try_from(value: Value) -> Result<Self, Self::Error> {
838 match value {
839 Value::Array(x) => Ok(x.into()),
840 _ => Err(Error::TryFrom(value.to_string(), "Vec<Value>")),
841 }
842 }
843}
844
845impl TryFrom<Value> for Number {
846 type Error = Error;
847 fn try_from(value: Value) -> Result<Self, Self::Error> {
848 match value {
849 Value::Number(x) => Ok(x),
850 _ => Err(Error::TryFrom(value.to_string(), "Number")),
851 }
852 }
853}
854
855impl TryFrom<&Value> for Number {
856 type Error = Error;
857 fn try_from(value: &Value) -> Result<Self, Self::Error> {
858 match value {
859 Value::Number(x) => Ok(*x),
860 _ => Err(Error::TryFrom(value.to_string(), "Number")),
861 }
862 }
863}
864
865impl TryFrom<Value> for Datetime {
866 type Error = Error;
867 fn try_from(value: Value) -> Result<Self, Self::Error> {
868 match value {
869 Value::Datetime(x) => Ok(x),
870 _ => Err(Error::TryFrom(value.to_string(), "Datetime")),
871 }
872 }
873}
874
875impl TryFrom<Value> for Object {
876 type Error = Error;
877 fn try_from(value: Value) -> Result<Self, Self::Error> {
878 match value {
879 Value::Object(x) => Ok(x),
880 _ => Err(Error::TryFrom(value.to_string(), "Object")),
881 }
882 }
883}
884
885impl FromIterator<Value> for Value {
886 fn from_iter<I: IntoIterator<Item = Value>>(iter: I) -> Self {
887 Value::Array(Array(iter.into_iter().collect()))
888 }
889}
890
891impl FromIterator<(String, Value)> for Value {
892 fn from_iter<I: IntoIterator<Item = (String, Value)>>(iter: I) -> Self {
893 Value::Object(Object(iter.into_iter().collect()))
894 }
895}
896
897impl Value {
898 pub fn base() -> Self {
904 Value::Object(Object::default())
905 }
906
907 pub fn ok(self) -> Result<Value, Error> {
913 Ok(self)
914 }
915
916 pub fn some(self) -> Option<Value> {
918 match self {
919 Value::None => None,
920 val => Some(val),
921 }
922 }
923
924 pub fn is_none_or_null(&self) -> bool {
930 matches!(self, Value::None | Value::Null)
931 }
932
933 pub fn is_none(&self) -> bool {
935 matches!(self, Value::None)
936 }
937
938 pub fn is_empty_array(&self) -> bool {
940 if let Value::Array(v) = self {
941 v.is_empty()
942 } else {
943 false
944 }
945 }
946
947 pub fn is_null(&self) -> bool {
949 matches!(self, Value::Null)
950 }
951
952 pub fn is_some(&self) -> bool {
954 !self.is_none() && !self.is_null()
955 }
956
957 pub fn is_bool(&self) -> bool {
959 matches!(self, Value::Bool(_))
960 }
961
962 pub fn is_true(&self) -> bool {
964 matches!(self, Value::Bool(true))
965 }
966
967 pub fn is_false(&self) -> bool {
969 matches!(self, Value::Bool(false))
970 }
971
972 pub fn is_truthy(&self) -> bool {
974 match self {
975 Value::Bool(v) => *v,
976 Value::Uuid(_) => true,
977 Value::Thing(_) => true,
978 Value::Geometry(_) => true,
979 Value::Datetime(_) => true,
980 Value::Array(v) => !v.is_empty(),
981 Value::Object(v) => !v.is_empty(),
982 Value::Strand(v) => !v.is_empty(),
983 Value::Number(v) => v.is_truthy(),
984 Value::Duration(v) => v.as_nanos() > 0,
985 _ => false,
986 }
987 }
988
989 pub fn is_uuid(&self) -> bool {
991 matches!(self, Value::Uuid(_))
992 }
993
994 pub fn is_thing(&self) -> bool {
996 matches!(self, Value::Thing(_))
997 }
998
999 pub fn is_thing_single(&self) -> bool {
1001 match self {
1002 Value::Thing(t) => !matches!(t.id, Id::Range(_)),
1003 _ => false,
1004 }
1005 }
1006
1007 pub fn is_thing_range(&self) -> bool {
1009 matches!(
1010 self,
1011 Value::Thing(Thing {
1012 id: Id::Range(_),
1013 ..
1014 })
1015 )
1016 }
1017
1018 pub fn is_mock(&self) -> bool {
1020 matches!(self, Value::Mock(_))
1021 }
1022
1023 pub fn is_param(&self) -> bool {
1025 matches!(self, Value::Param(_))
1026 }
1027
1028 pub fn is_range(&self) -> bool {
1030 matches!(self, Value::Range(_))
1031 }
1032
1033 pub fn is_table(&self) -> bool {
1035 matches!(self, Value::Table(_))
1036 }
1037
1038 pub fn is_strand(&self) -> bool {
1040 matches!(self, Value::Strand(_))
1041 }
1042
1043 pub fn is_query(&self) -> bool {
1045 matches!(self, Value::Query(_))
1046 }
1047
1048 pub fn is_bytes(&self) -> bool {
1050 matches!(self, Value::Bytes(_))
1051 }
1052
1053 pub fn is_array(&self) -> bool {
1055 matches!(self, Value::Array(_))
1056 }
1057
1058 pub fn is_object(&self) -> bool {
1060 matches!(self, Value::Object(_))
1061 }
1062
1063 pub fn is_number(&self) -> bool {
1065 matches!(self, Value::Number(_))
1066 }
1067
1068 pub fn is_datetime(&self) -> bool {
1070 matches!(self, Value::Datetime(_))
1071 }
1072
1073 pub fn is_duration(&self) -> bool {
1075 matches!(self, Value::Duration(_))
1076 }
1077
1078 pub fn is_record(&self) -> bool {
1080 matches!(self, Value::Thing(_))
1081 }
1082
1083 pub fn is_closure(&self) -> bool {
1085 matches!(self, Value::Closure(_))
1086 }
1087
1088 pub fn is_record_of_table(&self, table: String) -> bool {
1090 match self {
1091 Value::Thing(Thing {
1092 tb,
1093 ..
1094 }) => *tb == table,
1095 _ => false,
1096 }
1097 }
1098
1099 pub fn is_geometry(&self) -> bool {
1101 matches!(self, Value::Geometry(_))
1102 }
1103
1104 pub fn is_int(&self) -> bool {
1106 matches!(self, Value::Number(Number::Int(_)))
1107 }
1108
1109 pub fn is_float(&self) -> bool {
1111 matches!(self, Value::Number(Number::Float(_)))
1112 }
1113
1114 pub fn is_decimal(&self) -> bool {
1116 matches!(self, Value::Number(Number::Decimal(_)))
1117 }
1118
1119 pub fn is_nan(&self) -> bool {
1121 matches!(self, Value::Number(v) if v.is_nan())
1122 }
1123
1124 pub fn is_integer(&self) -> bool {
1126 matches!(self, Value::Number(v) if v.is_integer())
1127 }
1128
1129 pub fn is_positive(&self) -> bool {
1131 matches!(self, Value::Number(v) if v.is_positive())
1132 }
1133
1134 pub fn is_negative(&self) -> bool {
1136 matches!(self, Value::Number(v) if v.is_negative())
1137 }
1138
1139 pub fn is_zero_or_positive(&self) -> bool {
1141 matches!(self, Value::Number(v) if v.is_zero_or_positive())
1142 }
1143
1144 pub fn is_zero_or_negative(&self) -> bool {
1146 matches!(self, Value::Number(v) if v.is_zero_or_negative())
1147 }
1148
1149 pub fn is_record_type(&self, types: &[Table]) -> bool {
1151 match self {
1152 Value::Thing(v) => v.is_record_type(types),
1153 _ => false,
1154 }
1155 }
1156
1157 pub fn is_geometry_type(&self, types: &[String]) -> bool {
1159 match self {
1160 Value::Geometry(Geometry::Point(_)) => {
1161 types.iter().any(|t| matches!(t.as_str(), "feature" | "point"))
1162 }
1163 Value::Geometry(Geometry::Line(_)) => {
1164 types.iter().any(|t| matches!(t.as_str(), "feature" | "line"))
1165 }
1166 Value::Geometry(Geometry::Polygon(_)) => {
1167 types.iter().any(|t| matches!(t.as_str(), "feature" | "polygon"))
1168 }
1169 Value::Geometry(Geometry::MultiPoint(_)) => {
1170 types.iter().any(|t| matches!(t.as_str(), "feature" | "multipoint"))
1171 }
1172 Value::Geometry(Geometry::MultiLine(_)) => {
1173 types.iter().any(|t| matches!(t.as_str(), "feature" | "multiline"))
1174 }
1175 Value::Geometry(Geometry::MultiPolygon(_)) => {
1176 types.iter().any(|t| matches!(t.as_str(), "feature" | "multipolygon"))
1177 }
1178 Value::Geometry(Geometry::Collection(_)) => {
1179 types.iter().any(|t| matches!(t.as_str(), "feature" | "collection"))
1180 }
1181 _ => false,
1182 }
1183 }
1184
1185 pub fn is_single(&self) -> bool {
1186 match self {
1187 Value::Object(_) => true,
1188 t @ Value::Thing(_) => t.is_thing_single(),
1189 _ => false,
1190 }
1191 }
1192
1193 pub fn as_string(self) -> String {
1199 match self {
1200 Value::Strand(v) => v.0,
1201 Value::Uuid(v) => v.to_raw(),
1202 Value::Datetime(v) => v.to_raw(),
1203 _ => self.to_string(),
1204 }
1205 }
1206
1207 pub fn as_raw_string(self) -> String {
1209 match self {
1210 Value::Strand(v) => v.0,
1211 Value::Uuid(v) => v.to_raw(),
1212 Value::Datetime(v) => v.to_raw(),
1213 _ => self.to_string(),
1214 }
1215 }
1216
1217 pub fn to_raw_string(&self) -> String {
1223 match self {
1224 Value::Strand(v) => v.0.to_owned(),
1225 Value::Uuid(v) => v.to_raw(),
1226 Value::Datetime(v) => v.to_raw(),
1227 _ => self.to_string(),
1228 }
1229 }
1230
1231 pub fn to_idiom(&self) -> Idiom {
1233 match self {
1234 Value::Idiom(v) => v.simplify(),
1235 Value::Param(v) => v.to_raw().into(),
1236 Value::Strand(v) => v.0.to_string().into(),
1237 Value::Datetime(v) => v.0.to_string().into(),
1238 Value::Future(_) => "future".to_string().into(),
1239 Value::Function(v) => v.to_idiom(),
1240 _ => self.to_string().into(),
1241 }
1242 }
1243
1244 pub fn can_start_idiom(&self) -> bool {
1246 match self {
1247 Value::Function(x) => !x.is_script(),
1248 Value::Model(_)
1249 | Value::Subquery(_)
1250 | Value::Constant(_)
1251 | Value::Datetime(_)
1252 | Value::Duration(_)
1253 | Value::Uuid(_)
1254 | Value::Number(_)
1255 | Value::Object(_)
1256 | Value::Array(_)
1257 | Value::Param(_)
1258 | Value::Edges(_)
1259 | Value::Thing(_)
1260 | Value::Table(_) => true,
1261 _ => false,
1262 }
1263 }
1264
1265 pub fn to_operations(&self) -> Result<Vec<Operation>, Error> {
1267 match self {
1268 Value::Array(v) => v
1269 .iter()
1270 .map(|v| match v {
1271 Value::Object(v) => v.to_operation(),
1272 _ => Err(Error::InvalidPatch {
1273 message: String::from("Operation must be an object"),
1274 }),
1275 })
1276 .collect::<Result<Vec<_>, Error>>(),
1277 _ => Err(Error::InvalidPatch {
1278 message: String::from("Operations must be an array"),
1279 }),
1280 }
1281 }
1282
1283 pub fn into_json(self) -> Json {
1288 self.into()
1289 }
1290
1291 pub fn could_be_table(self) -> Value {
1297 match self {
1298 Value::Strand(v) => Value::Table(v.0.into()),
1299 _ => self,
1300 }
1301 }
1302
1303 pub fn kindof(&self) -> &'static str {
1309 match self {
1310 Self::None => "none",
1311 Self::Null => "null",
1312 Self::Bool(_) => "bool",
1313 Self::Uuid(_) => "uuid",
1314 Self::Array(_) => "array",
1315 Self::Object(_) => "object",
1316 Self::Strand(_) => "string",
1317 Self::Duration(_) => "duration",
1318 Self::Datetime(_) => "datetime",
1319 Self::Closure(_) => "function",
1320 Self::Number(Number::Int(_)) => "int",
1321 Self::Number(Number::Float(_)) => "float",
1322 Self::Number(Number::Decimal(_)) => "decimal",
1323 Self::Geometry(Geometry::Point(_)) => "geometry<point>",
1324 Self::Geometry(Geometry::Line(_)) => "geometry<line>",
1325 Self::Geometry(Geometry::Polygon(_)) => "geometry<polygon>",
1326 Self::Geometry(Geometry::MultiPoint(_)) => "geometry<multipoint>",
1327 Self::Geometry(Geometry::MultiLine(_)) => "geometry<multiline>",
1328 Self::Geometry(Geometry::MultiPolygon(_)) => "geometry<multipolygon>",
1329 Self::Geometry(Geometry::Collection(_)) => "geometry<collection>",
1330 Self::Bytes(_) => "bytes",
1331 Self::Range(_) => "range",
1332 _ => "incorrect type",
1333 }
1334 }
1335
1336 pub(crate) fn coerce_to(self, kind: &Kind) -> Result<Value, Error> {
1342 let res = match kind {
1344 Kind::Any => Ok(self),
1345 Kind::Null => self.coerce_to_null(),
1346 Kind::Bool => self.coerce_to_bool().map(Value::from),
1347 Kind::Int => self.coerce_to_int().map(Value::from),
1348 Kind::Float => self.coerce_to_float().map(Value::from),
1349 Kind::Decimal => self.coerce_to_decimal().map(Value::from),
1350 Kind::Number => self.coerce_to_number().map(Value::from),
1351 Kind::String => self.coerce_to_strand().map(Value::from),
1352 Kind::Datetime => self.coerce_to_datetime().map(Value::from),
1353 Kind::Duration => self.coerce_to_duration().map(Value::from),
1354 Kind::Object => self.coerce_to_object().map(Value::from),
1355 Kind::Point => self.coerce_to_point().map(Value::from),
1356 Kind::Bytes => self.coerce_to_bytes().map(Value::from),
1357 Kind::Uuid => self.coerce_to_uuid().map(Value::from),
1358 Kind::Range => self.coerce_to_range().map(Value::from),
1359 Kind::Function(_, _) => self.coerce_to_function().map(Value::from),
1360 Kind::Set(t, l) => match l {
1361 Some(l) => self.coerce_to_set_type_len(t, l).map(Value::from),
1362 None => self.coerce_to_set_type(t).map(Value::from),
1363 },
1364 Kind::Array(t, l) => match l {
1365 Some(l) => self.coerce_to_array_type_len(t, l).map(Value::from),
1366 None => self.coerce_to_array_type(t).map(Value::from),
1367 },
1368 Kind::Record(t) => match t.is_empty() {
1369 true => self.coerce_to_record().map(Value::from),
1370 false => self.coerce_to_record_type(t).map(Value::from),
1371 },
1372 Kind::Geometry(t) => match t.is_empty() {
1373 true => self.coerce_to_geometry().map(Value::from),
1374 false => self.coerce_to_geometry_type(t).map(Value::from),
1375 },
1376 Kind::Option(k) => match self {
1377 Self::None => Ok(Self::None),
1378 v => v.coerce_to(k),
1379 },
1380 Kind::Either(k) => {
1381 let mut val = self;
1382 for k in k {
1383 match val.coerce_to(k) {
1384 Err(Error::CoerceTo {
1385 from,
1386 ..
1387 }) => val = from,
1388 Err(e) => return Err(e),
1389 Ok(v) => return Ok(v),
1390 }
1391 }
1392 Err(Error::CoerceTo {
1393 from: val,
1394 into: kind.to_string(),
1395 })
1396 }
1397 Kind::Literal(lit) => self.coerce_to_literal(lit),
1398 Kind::References(_, _) => Err(Error::CoerceTo {
1399 from: self,
1400 into: kind.to_string(),
1401 }),
1402 };
1403 match res {
1405 Err(Error::CoerceTo {
1407 from,
1408 ..
1409 }) => Err(Error::CoerceTo {
1410 from,
1411 into: kind.to_string(),
1412 }),
1413 Err(e) => Err(e),
1415 Ok(v) => Ok(v),
1417 }
1418 }
1419
1420 pub fn coerce_to_i64(self) -> Result<i64, Error> {
1422 match self {
1423 Value::Number(Number::Int(v)) => Ok(v),
1425 Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(v as i64),
1427 Value::Number(Number::Decimal(v)) if v.is_integer() => match v.try_into() {
1429 Ok(v) => Ok(v),
1431 _ => Err(Error::CoerceTo {
1433 from: self,
1434 into: "i64".into(),
1435 }),
1436 },
1437 _ => Err(Error::CoerceTo {
1439 from: self,
1440 into: "i64".into(),
1441 }),
1442 }
1443 }
1444
1445 pub(crate) fn coerce_to_u64(self) -> Result<u64, Error> {
1447 match self {
1448 Value::Number(Number::Int(v)) => Ok(v as u64),
1450 Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(v as u64),
1452 Value::Number(Number::Decimal(v)) if v.is_integer() => match v.try_into() {
1454 Ok(v) => Ok(v),
1456 _ => Err(Error::CoerceTo {
1458 from: self,
1459 into: "u64".into(),
1460 }),
1461 },
1462 _ => Err(Error::CoerceTo {
1464 from: self,
1465 into: "u64".into(),
1466 }),
1467 }
1468 }
1469
1470 pub(crate) fn coerce_to_f64(self) -> Result<f64, Error> {
1472 match self {
1473 Value::Number(Number::Float(v)) => Ok(v),
1475 Value::Number(Number::Int(v)) => Ok(v as f64),
1477 Value::Number(Number::Decimal(v)) => match v.try_into() {
1479 Ok(v) => Ok(v),
1481 _ => Err(Error::CoerceTo {
1483 from: self,
1484 into: "f64".into(),
1485 }),
1486 },
1487 _ => Err(Error::CoerceTo {
1489 from: self,
1490 into: "f64".into(),
1491 }),
1492 }
1493 }
1494
1495 pub(crate) fn coerce_to_literal(self, literal: &Literal) -> Result<Value, Error> {
1497 if literal.validate_value(&self) {
1498 Ok(self)
1499 } else {
1500 Err(Error::CoerceTo {
1501 from: self,
1502 into: literal.to_string(),
1503 })
1504 }
1505 }
1506
1507 pub(crate) fn coerce_to_null(self) -> Result<Value, Error> {
1509 match self {
1510 Value::Null => Ok(Value::Null),
1512 _ => Err(Error::CoerceTo {
1514 from: self,
1515 into: "null".into(),
1516 }),
1517 }
1518 }
1519
1520 pub(crate) fn coerce_to_bool(self) -> Result<bool, Error> {
1522 match self {
1523 Value::Bool(v) => Ok(v),
1525 _ => Err(Error::CoerceTo {
1527 from: self,
1528 into: "bool".into(),
1529 }),
1530 }
1531 }
1532
1533 pub(crate) fn coerce_to_int(self) -> Result<Number, Error> {
1535 match self {
1536 Value::Number(v) if v.is_int() => Ok(v),
1538 Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(Number::Int(v as i64)),
1540 Value::Number(Number::Decimal(v)) if v.is_integer() => match v.to_i64() {
1542 Some(v) => Ok(Number::Int(v)),
1544 _ => Err(Error::CoerceTo {
1546 from: self,
1547 into: "int".into(),
1548 }),
1549 },
1550 _ => Err(Error::CoerceTo {
1552 from: self,
1553 into: "int".into(),
1554 }),
1555 }
1556 }
1557
1558 pub(crate) fn coerce_to_float(self) -> Result<Number, Error> {
1560 match self {
1561 Value::Number(v) if v.is_float() => Ok(v),
1563 Value::Number(Number::Int(v)) => Ok(Number::Float(v as f64)),
1565 Value::Number(Number::Decimal(ref v)) => match v.to_f64() {
1567 Some(v) => Ok(Number::Float(v)),
1569 None => Err(Error::CoerceTo {
1571 from: self,
1572 into: "float".into(),
1573 }),
1574 },
1575 _ => Err(Error::CoerceTo {
1577 from: self,
1578 into: "float".into(),
1579 }),
1580 }
1581 }
1582
1583 pub(crate) fn coerce_to_decimal(self) -> Result<Number, Error> {
1585 match self {
1586 Value::Number(v) if v.is_decimal() => Ok(v),
1588 Value::Number(Number::Int(v)) => match Decimal::from_i64(v) {
1590 Some(v) => Ok(Number::Decimal(v)),
1592 None => Err(Error::CoerceTo {
1594 from: self,
1595 into: "decimal".into(),
1596 }),
1597 },
1598 Value::Number(Number::Float(v)) => match Decimal::from_f64(v) {
1600 Some(v) => Ok(Number::Decimal(v)),
1602 None => Err(Error::CoerceTo {
1604 from: self,
1605 into: "decimal".into(),
1606 }),
1607 },
1608 _ => Err(Error::CoerceTo {
1610 from: self,
1611 into: "decimal".into(),
1612 }),
1613 }
1614 }
1615
1616 pub(crate) fn coerce_to_number(self) -> Result<Number, Error> {
1618 match self {
1619 Value::Number(v) => Ok(v),
1621 _ => Err(Error::CoerceTo {
1623 from: self,
1624 into: "number".into(),
1625 }),
1626 }
1627 }
1628
1629 pub(crate) fn coerce_to_regex(self) -> Result<Regex, Error> {
1631 match self {
1632 Value::Regex(v) => Ok(v),
1634 Value::Strand(v) => Ok(v.as_str().parse()?),
1636 _ => Err(Error::CoerceTo {
1638 from: self,
1639 into: "regex".into(),
1640 }),
1641 }
1642 }
1643
1644 pub(crate) fn coerce_to_string(self) -> Result<String, Error> {
1646 match self {
1647 Value::Uuid(v) => Ok(v.to_raw()),
1649 Value::Datetime(v) => Ok(v.to_raw()),
1651 Value::Strand(v) => Ok(v.as_string()),
1653 _ => Err(Error::CoerceTo {
1655 from: self,
1656 into: "string".into(),
1657 }),
1658 }
1659 }
1660
1661 pub(crate) fn coerce_to_strand(self) -> Result<Strand, Error> {
1663 match self {
1664 Value::Uuid(v) => Ok(v.to_raw().into()),
1666 Value::Datetime(v) => Ok(v.to_raw().into()),
1668 Value::Strand(v) => Ok(v),
1670 _ => Err(Error::CoerceTo {
1672 from: self,
1673 into: "string".into(),
1674 }),
1675 }
1676 }
1677
1678 pub(crate) fn coerce_to_uuid(self) -> Result<Uuid, Error> {
1680 match self {
1681 Value::Uuid(v) => Ok(v),
1683 _ => Err(Error::CoerceTo {
1685 from: self,
1686 into: "uuid".into(),
1687 }),
1688 }
1689 }
1690
1691 pub(crate) fn coerce_to_function(self) -> Result<Closure, Error> {
1693 match self {
1694 Value::Closure(v) => Ok(*v),
1696 _ => Err(Error::CoerceTo {
1698 from: self,
1699 into: "function".into(),
1700 }),
1701 }
1702 }
1703
1704 pub(crate) fn coerce_to_datetime(self) -> Result<Datetime, Error> {
1706 match self {
1707 Value::Datetime(v) => Ok(v),
1709 _ => Err(Error::CoerceTo {
1711 from: self,
1712 into: "datetime".into(),
1713 }),
1714 }
1715 }
1716
1717 pub(crate) fn coerce_to_duration(self) -> Result<Duration, Error> {
1719 match self {
1720 Value::Duration(v) => Ok(v),
1722 _ => Err(Error::CoerceTo {
1724 from: self,
1725 into: "duration".into(),
1726 }),
1727 }
1728 }
1729
1730 pub(crate) fn coerce_to_bytes(self) -> Result<Bytes, Error> {
1732 match self {
1733 Value::Bytes(v) => Ok(v),
1735 _ => Err(Error::CoerceTo {
1737 from: self,
1738 into: "bytes".into(),
1739 }),
1740 }
1741 }
1742
1743 pub(crate) fn coerce_to_object(self) -> Result<Object, Error> {
1745 match self {
1746 Value::Object(v) => Ok(v),
1748 _ => Err(Error::CoerceTo {
1750 from: self,
1751 into: "object".into(),
1752 }),
1753 }
1754 }
1755
1756 pub(crate) fn coerce_to_array(self) -> Result<Array, Error> {
1758 match self {
1759 Value::Array(v) => Ok(v),
1761 _ => Err(Error::CoerceTo {
1763 from: self,
1764 into: "array".into(),
1765 }),
1766 }
1767 }
1768
1769 pub(crate) fn coerce_to_range(self) -> Result<Range, Error> {
1771 match self {
1772 Value::Range(v) => Ok(*v),
1774 _ => Err(Error::CoerceTo {
1776 from: self,
1777 into: "range".into(),
1778 }),
1779 }
1780 }
1781
1782 pub(crate) fn coerce_to_point(self) -> Result<Geometry, Error> {
1784 match self {
1785 Value::Geometry(Geometry::Point(v)) => Ok(v.into()),
1787 _ => Err(Error::CoerceTo {
1789 from: self,
1790 into: "point".into(),
1791 }),
1792 }
1793 }
1794
1795 pub(crate) fn coerce_to_record(self) -> Result<Thing, Error> {
1797 match self {
1798 Value::Thing(v) => Ok(v),
1800 _ => Err(Error::CoerceTo {
1802 from: self,
1803 into: "record".into(),
1804 }),
1805 }
1806 }
1807
1808 pub(crate) fn coerce_to_geometry(self) -> Result<Geometry, Error> {
1810 match self {
1811 Value::Geometry(v) => Ok(v),
1813 _ => Err(Error::CoerceTo {
1815 from: self,
1816 into: "geometry".into(),
1817 }),
1818 }
1819 }
1820
1821 pub(crate) fn coerce_to_record_type(self, val: &[Table]) -> Result<Thing, Error> {
1823 match self {
1824 Value::Thing(v) if self.is_record_type(val) => Ok(v),
1826 _ => Err(Error::CoerceTo {
1828 from: self,
1829 into: "record".into(),
1830 }),
1831 }
1832 }
1833
1834 pub(crate) fn coerce_to_geometry_type(self, val: &[String]) -> Result<Geometry, Error> {
1836 match self {
1837 Value::Geometry(v) if self.is_geometry_type(val) => Ok(v),
1839 _ => Err(Error::CoerceTo {
1841 from: self,
1842 into: "geometry".into(),
1843 }),
1844 }
1845 }
1846
1847 pub(crate) fn coerce_to_array_type(self, kind: &Kind) -> Result<Array, Error> {
1849 self.coerce_to_array()?
1850 .into_iter()
1851 .map(|value| value.coerce_to(kind))
1852 .collect::<Result<Array, Error>>()
1853 .map_err(|e| match e {
1854 Error::CoerceTo {
1855 from,
1856 ..
1857 } => Error::CoerceTo {
1858 from,
1859 into: format!("array<{kind}>"),
1860 },
1861 e => e,
1862 })
1863 }
1864
1865 pub(crate) fn coerce_to_array_type_len(self, kind: &Kind, len: &u64) -> Result<Array, Error> {
1867 self.coerce_to_array()?
1868 .into_iter()
1869 .map(|value| value.coerce_to(kind))
1870 .collect::<Result<Array, Error>>()
1871 .map_err(|e| match e {
1872 Error::CoerceTo {
1873 from,
1874 ..
1875 } => Error::CoerceTo {
1876 from,
1877 into: format!("array<{kind}, {len}>"),
1878 },
1879 e => e,
1880 })
1881 .and_then(|v| match v.len() {
1882 v if v > *len as usize => Err(Error::LengthInvalid {
1883 kind: format!("array<{kind}, {len}>"),
1884 size: v,
1885 }),
1886 _ => Ok(v),
1887 })
1888 }
1889
1890 pub(crate) fn coerce_to_set_type(self, kind: &Kind) -> Result<Array, Error> {
1892 self.coerce_to_array()?
1893 .uniq()
1894 .into_iter()
1895 .map(|value| value.coerce_to(kind))
1896 .collect::<Result<Array, Error>>()
1897 .map_err(|e| match e {
1898 Error::CoerceTo {
1899 from,
1900 ..
1901 } => Error::CoerceTo {
1902 from,
1903 into: format!("set<{kind}>"),
1904 },
1905 e => e,
1906 })
1907 }
1908
1909 pub(crate) fn coerce_to_set_type_len(self, kind: &Kind, len: &u64) -> Result<Array, Error> {
1911 self.coerce_to_array()?
1912 .uniq()
1913 .into_iter()
1914 .map(|value| value.coerce_to(kind))
1915 .collect::<Result<Array, Error>>()
1916 .map_err(|e| match e {
1917 Error::CoerceTo {
1918 from,
1919 ..
1920 } => Error::CoerceTo {
1921 from,
1922 into: format!("set<{kind}, {len}>"),
1923 },
1924 e => e,
1925 })
1926 .and_then(|v| match v.len() {
1927 v if v > *len as usize => Err(Error::LengthInvalid {
1928 kind: format!("set<{kind}, {len}>"),
1929 size: v,
1930 }),
1931 _ => Ok(v),
1932 })
1933 }
1934
1935 pub(crate) fn convert_to(self, kind: &Kind) -> Result<Value, Error> {
1941 let res = match kind {
1943 Kind::Any => Ok(self),
1944 Kind::Null => self.convert_to_null(),
1945 Kind::Bool => self.convert_to_bool().map(Value::from),
1946 Kind::Int => self.convert_to_int().map(Value::from),
1947 Kind::Float => self.convert_to_float().map(Value::from),
1948 Kind::Decimal => self.convert_to_decimal().map(Value::from),
1949 Kind::Number => self.convert_to_number().map(Value::from),
1950 Kind::String => self.convert_to_strand().map(Value::from),
1951 Kind::Datetime => self.convert_to_datetime().map(Value::from),
1952 Kind::Duration => self.convert_to_duration().map(Value::from),
1953 Kind::Object => self.convert_to_object().map(Value::from),
1954 Kind::Point => self.convert_to_point().map(Value::from),
1955 Kind::Bytes => self.convert_to_bytes().map(Value::from),
1956 Kind::Uuid => self.convert_to_uuid().map(Value::from),
1957 Kind::Range => self.convert_to_range().map(Value::from),
1958 Kind::Function(_, _) => self.convert_to_function().map(Value::from),
1959 Kind::Set(t, l) => match l {
1960 Some(l) => self.convert_to_set_type_len(t, l).map(Value::from),
1961 None => self.convert_to_set_type(t).map(Value::from),
1962 },
1963 Kind::Array(t, l) => match l {
1964 Some(l) => self.convert_to_array_type_len(t, l).map(Value::from),
1965 None => self.convert_to_array_type(t).map(Value::from),
1966 },
1967 Kind::Record(t) => match t.is_empty() {
1968 true => self.convert_to_record().map(Value::from),
1969 false => self.convert_to_record_type(t).map(Value::from),
1970 },
1971 Kind::Geometry(t) => match t.is_empty() {
1972 true => self.convert_to_geometry().map(Value::from),
1973 false => self.convert_to_geometry_type(t).map(Value::from),
1974 },
1975 Kind::Option(k) => match self {
1976 Self::None => Ok(Self::None),
1977 v => v.convert_to(k),
1978 },
1979 Kind::Either(k) => {
1980 let mut val = self;
1981 for k in k {
1982 match val.convert_to(k) {
1983 Err(Error::ConvertTo {
1984 from,
1985 ..
1986 }) => val = from,
1987 Err(e) => return Err(e),
1988 Ok(v) => return Ok(v),
1989 }
1990 }
1991 Err(Error::ConvertTo {
1992 from: val,
1993 into: kind.to_string(),
1994 })
1995 }
1996 Kind::Literal(lit) => self.convert_to_literal(lit),
1997 Kind::References(_, _) => Err(Error::CoerceTo {
1998 from: self,
1999 into: kind.to_string(),
2000 }),
2001 };
2002 match res {
2004 Err(Error::ConvertTo {
2006 from,
2007 ..
2008 }) => Err(Error::ConvertTo {
2009 from,
2010 into: kind.to_string(),
2011 }),
2012 Err(e) => Err(e),
2014 Ok(v) => Ok(v),
2016 }
2017 }
2018
2019 pub(crate) fn convert_to_literal(self, literal: &Literal) -> Result<Value, Error> {
2021 if literal.validate_value(&self) {
2022 Ok(self)
2023 } else {
2024 Err(Error::ConvertTo {
2025 from: self,
2026 into: literal.to_string(),
2027 })
2028 }
2029 }
2030
2031 pub(crate) fn convert_to_null(self) -> Result<Value, Error> {
2033 match self {
2034 Value::Null => Ok(Value::Null),
2036 _ => Err(Error::ConvertTo {
2038 from: self,
2039 into: "null".into(),
2040 }),
2041 }
2042 }
2043
2044 pub(crate) fn convert_to_bool(self) -> Result<bool, Error> {
2046 match self {
2047 Value::Bool(v) => Ok(v),
2049 Value::Strand(ref v) => match v.parse::<bool>() {
2051 Ok(v) => Ok(v),
2053 _ => Err(Error::ConvertTo {
2055 from: self,
2056 into: "bool".into(),
2057 }),
2058 },
2059 _ => Err(Error::ConvertTo {
2061 from: self,
2062 into: "bool".into(),
2063 }),
2064 }
2065 }
2066
2067 pub(crate) fn convert_to_int(self) -> Result<Number, Error> {
2069 match self {
2070 Value::Number(v) if v.is_int() => Ok(v),
2072 Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(Number::Int(v as i64)),
2074 Value::Number(Number::Decimal(v)) if v.is_integer() => match v.try_into() {
2076 Ok(v) => Ok(Number::Int(v)),
2078 _ => Err(Error::ConvertTo {
2080 from: self,
2081 into: "int".into(),
2082 }),
2083 },
2084 Value::Strand(ref v) => match v.parse::<i64>() {
2086 Ok(v) => Ok(Number::Int(v)),
2088 _ => Err(Error::ConvertTo {
2090 from: self,
2091 into: "int".into(),
2092 }),
2093 },
2094 _ => Err(Error::ConvertTo {
2096 from: self,
2097 into: "int".into(),
2098 }),
2099 }
2100 }
2101
2102 pub(crate) fn convert_to_float(self) -> Result<Number, Error> {
2104 match self {
2105 Value::Number(v) if v.is_float() => Ok(v),
2107 Value::Number(Number::Int(v)) => Ok(Number::Float(v as f64)),
2109 Value::Number(Number::Decimal(v)) => match v.try_into() {
2111 Ok(v) => Ok(Number::Float(v)),
2113 _ => Err(Error::ConvertTo {
2115 from: self,
2116 into: "float".into(),
2117 }),
2118 },
2119 Value::Strand(ref v) => match v.parse::<f64>() {
2121 Ok(v) => Ok(Number::Float(v)),
2123 _ => Err(Error::ConvertTo {
2125 from: self,
2126 into: "float".into(),
2127 }),
2128 },
2129 _ => Err(Error::ConvertTo {
2131 from: self,
2132 into: "float".into(),
2133 }),
2134 }
2135 }
2136
2137 pub(crate) fn convert_to_decimal(self) -> Result<Number, Error> {
2139 match self {
2140 Value::Number(v) if v.is_decimal() => Ok(v),
2142 Value::Number(Number::Int(ref v)) => Ok(Number::Decimal(Decimal::from(*v))),
2144 Value::Number(Number::Float(ref v)) => match Decimal::try_from(*v) {
2146 Ok(v) => Ok(Number::Decimal(v)),
2148 _ => Err(Error::ConvertTo {
2150 from: self,
2151 into: "decimal".into(),
2152 }),
2153 },
2154 Value::Strand(ref v) => match Decimal::from_str(v) {
2156 Ok(v) => Ok(Number::Decimal(v)),
2158 _ => Err(Error::ConvertTo {
2160 from: self,
2161 into: "decimal".into(),
2162 }),
2163 },
2164 _ => Err(Error::ConvertTo {
2166 from: self,
2167 into: "decimal".into(),
2168 }),
2169 }
2170 }
2171
2172 pub(crate) fn convert_to_number(self) -> Result<Number, Error> {
2174 match self {
2175 Value::Number(v) => Ok(v),
2177 Value::Strand(ref v) => match Number::from_str(v) {
2179 Ok(v) => Ok(v),
2181 _ => Err(Error::ConvertTo {
2183 from: self,
2184 into: "number".into(),
2185 }),
2186 },
2187 _ => Err(Error::ConvertTo {
2189 from: self,
2190 into: "number".into(),
2191 }),
2192 }
2193 }
2194
2195 pub fn convert_to_string(self) -> Result<String, Error> {
2197 match self {
2198 Value::Bytes(_) => Err(Error::ConvertTo {
2200 from: self,
2201 into: "string".into(),
2202 }),
2203 Value::None => Err(Error::ConvertTo {
2205 from: self,
2206 into: "string".into(),
2207 }),
2208 Value::Null => Err(Error::ConvertTo {
2210 from: self,
2211 into: "string".into(),
2212 }),
2213 _ => Ok(self.as_string()),
2215 }
2216 }
2217
2218 pub(crate) fn convert_to_strand(self) -> Result<Strand, Error> {
2220 match self {
2221 Value::Bytes(_) => Err(Error::ConvertTo {
2223 from: self,
2224 into: "string".into(),
2225 }),
2226 Value::None => Err(Error::ConvertTo {
2228 from: self,
2229 into: "string".into(),
2230 }),
2231 Value::Null => Err(Error::ConvertTo {
2233 from: self,
2234 into: "string".into(),
2235 }),
2236 Value::Strand(v) => Ok(v),
2238 Value::Uuid(v) => Ok(v.to_raw().into()),
2240 Value::Datetime(v) => Ok(v.to_raw().into()),
2242 _ => Ok(self.to_string().into()),
2244 }
2245 }
2246
2247 pub(crate) fn convert_to_uuid(self) -> Result<Uuid, Error> {
2249 match self {
2250 Value::Uuid(v) => Ok(v),
2252 Value::Strand(ref v) => match Uuid::from_str(v) {
2254 Ok(v) => Ok(v),
2256 _ => Err(Error::ConvertTo {
2258 from: self,
2259 into: "uuid".into(),
2260 }),
2261 },
2262 _ => Err(Error::ConvertTo {
2264 from: self,
2265 into: "uuid".into(),
2266 }),
2267 }
2268 }
2269
2270 pub(crate) fn convert_to_function(self) -> Result<Closure, Error> {
2272 match self {
2273 Value::Closure(v) => Ok(*v),
2275 _ => Err(Error::ConvertTo {
2277 from: self,
2278 into: "function".into(),
2279 }),
2280 }
2281 }
2282
2283 pub(crate) fn convert_to_datetime(self) -> Result<Datetime, Error> {
2285 match self {
2286 Value::Datetime(v) => Ok(v),
2288 Value::Strand(ref v) => match Datetime::from_str(v) {
2290 Ok(v) => Ok(v),
2292 _ => Err(Error::ConvertTo {
2294 from: self,
2295 into: "datetime".into(),
2296 }),
2297 },
2298 _ => Err(Error::ConvertTo {
2300 from: self,
2301 into: "datetime".into(),
2302 }),
2303 }
2304 }
2305
2306 pub(crate) fn convert_to_duration(self) -> Result<Duration, Error> {
2308 match self {
2309 Value::Duration(v) => Ok(v),
2311 Value::Strand(ref v) => match Duration::from_str(v) {
2313 Ok(v) => Ok(v),
2315 _ => Err(Error::ConvertTo {
2317 from: self,
2318 into: "duration".into(),
2319 }),
2320 },
2321 _ => Err(Error::ConvertTo {
2323 from: self,
2324 into: "duration".into(),
2325 }),
2326 }
2327 }
2328
2329 pub(crate) fn convert_to_bytes(self) -> Result<Bytes, Error> {
2331 match self {
2332 Value::Bytes(v) => Ok(v),
2334 Value::Strand(s) => Ok(Bytes(s.0.into_bytes())),
2336 _ => Err(Error::ConvertTo {
2338 from: self,
2339 into: "bytes".into(),
2340 }),
2341 }
2342 }
2343
2344 pub(crate) fn convert_to_object(self) -> Result<Object, Error> {
2346 match self {
2347 Value::Object(v) => Ok(v),
2349 _ => Err(Error::ConvertTo {
2351 from: self,
2352 into: "object".into(),
2353 }),
2354 }
2355 }
2356
2357 pub(crate) fn convert_to_array(self) -> Result<Array, Error> {
2359 match self {
2360 Value::Array(v) => Ok(v),
2362 Value::Range(r) => {
2364 let range: std::ops::Range<i64> = r.deref().to_owned().try_into()?;
2365 Ok(range.into_iter().map(Value::from).collect::<Vec<Value>>().into())
2366 }
2367 _ => Err(Error::ConvertTo {
2369 from: self,
2370 into: "array".into(),
2371 }),
2372 }
2373 }
2374
2375 pub(crate) fn convert_to_range(self) -> Result<Range, Error> {
2377 match self {
2378 Value::Range(r) => Ok(*r),
2380 Value::Array(v) if v.len() == 2 => {
2382 let mut v = v;
2383 Ok(Range {
2384 beg: Bound::Included(v.remove(0)),
2385 end: Bound::Excluded(v.remove(0)),
2386 })
2387 }
2388 _ => Err(Error::ConvertTo {
2390 from: self,
2391 into: "range".into(),
2392 }),
2393 }
2394 }
2395
2396 pub(crate) fn convert_to_point(self) -> Result<Geometry, Error> {
2398 match self {
2399 Value::Geometry(Geometry::Point(v)) => Ok(v.into()),
2401 Value::Array(ref v) if v.len() == 2 => match v.as_slice() {
2403 [Value::Number(v), Value::Number(w)] => Ok((v.to_float(), w.to_float()).into()),
2405 _ => Err(Error::ConvertTo {
2407 from: self,
2408 into: "point".into(),
2409 }),
2410 },
2411 _ => Err(Error::ConvertTo {
2413 from: self,
2414 into: "point".into(),
2415 }),
2416 }
2417 }
2418
2419 pub(crate) fn convert_to_record(self) -> Result<Thing, Error> {
2421 match self {
2422 Value::Thing(v) => Ok(v),
2424 Value::Strand(ref v) => match Thing::from_str(v) {
2426 Ok(v) => Ok(v),
2428 _ => Err(Error::ConvertTo {
2430 from: self,
2431 into: "record".into(),
2432 }),
2433 },
2434 _ => Err(Error::ConvertTo {
2436 from: self,
2437 into: "record".into(),
2438 }),
2439 }
2440 }
2441
2442 pub(crate) fn convert_to_geometry(self) -> Result<Geometry, Error> {
2444 match self {
2445 Value::Geometry(v) => Ok(v),
2447 _ => Err(Error::ConvertTo {
2449 from: self,
2450 into: "geometry".into(),
2451 }),
2452 }
2453 }
2454
2455 pub(crate) fn convert_to_record_type(self, val: &[Table]) -> Result<Thing, Error> {
2457 match self {
2458 Value::Thing(v) if self.is_record_type(val) => Ok(v),
2460 Value::Strand(ref v) => match Thing::from_str(v) {
2462 Ok(v) if v.is_record_type(val) => Ok(v),
2464 _ => Err(Error::ConvertTo {
2466 from: self,
2467 into: "record".into(),
2468 }),
2469 },
2470 _ => Err(Error::ConvertTo {
2472 from: self,
2473 into: "record".into(),
2474 }),
2475 }
2476 }
2477
2478 pub(crate) fn convert_to_geometry_type(self, val: &[String]) -> Result<Geometry, Error> {
2480 match self {
2481 Value::Geometry(v) if self.is_geometry_type(val) => Ok(v),
2483 _ => Err(Error::ConvertTo {
2485 from: self,
2486 into: "geometry".into(),
2487 }),
2488 }
2489 }
2490
2491 pub(crate) fn convert_to_array_type(self, kind: &Kind) -> Result<Array, Error> {
2493 self.convert_to_array()?
2494 .into_iter()
2495 .map(|value| value.convert_to(kind))
2496 .collect::<Result<Array, Error>>()
2497 .map_err(|e| match e {
2498 Error::ConvertTo {
2499 from,
2500 ..
2501 } => Error::ConvertTo {
2502 from,
2503 into: format!("array<{kind}>"),
2504 },
2505 e => e,
2506 })
2507 }
2508
2509 pub(crate) fn convert_to_array_type_len(self, kind: &Kind, len: &u64) -> Result<Array, Error> {
2511 self.convert_to_array()?
2512 .into_iter()
2513 .map(|value| value.convert_to(kind))
2514 .collect::<Result<Array, Error>>()
2515 .map_err(|e| match e {
2516 Error::ConvertTo {
2517 from,
2518 ..
2519 } => Error::ConvertTo {
2520 from,
2521 into: format!("array<{kind}, {len}>"),
2522 },
2523 e => e,
2524 })
2525 .and_then(|v| match v.len() {
2526 v if v > *len as usize => Err(Error::LengthInvalid {
2527 kind: format!("array<{kind}, {len}>"),
2528 size: v,
2529 }),
2530 _ => Ok(v),
2531 })
2532 }
2533
2534 pub(crate) fn convert_to_set_type(self, kind: &Kind) -> Result<Array, Error> {
2536 self.convert_to_array()?
2537 .uniq()
2538 .into_iter()
2539 .map(|value| value.convert_to(kind))
2540 .collect::<Result<Array, Error>>()
2541 .map_err(|e| match e {
2542 Error::ConvertTo {
2543 from,
2544 ..
2545 } => Error::ConvertTo {
2546 from,
2547 into: format!("set<{kind}>"),
2548 },
2549 e => e,
2550 })
2551 }
2552
2553 pub(crate) fn convert_to_set_type_len(self, kind: &Kind, len: &u64) -> Result<Array, Error> {
2555 self.convert_to_array()?
2556 .uniq()
2557 .into_iter()
2558 .map(|value| value.convert_to(kind))
2559 .collect::<Result<Array, Error>>()
2560 .map_err(|e| match e {
2561 Error::ConvertTo {
2562 from,
2563 ..
2564 } => Error::ConvertTo {
2565 from,
2566 into: format!("set<{kind}, {len}>"),
2567 },
2568 e => e,
2569 })
2570 .and_then(|v| match v.len() {
2571 v if v > *len as usize => Err(Error::LengthInvalid {
2572 kind: format!("set<{kind}, {len}>"),
2573 size: v,
2574 }),
2575 _ => Ok(v),
2576 })
2577 }
2578
2579 pub fn record(self) -> Option<Thing> {
2585 match self {
2586 Value::Object(mut v) => match v.remove("id") {
2588 Some(Value::Thing(v)) => Some(v),
2589 _ => None,
2590 },
2591 Value::Array(mut v) => match v.len() {
2593 1 => v.remove(0).record(),
2594 _ => None,
2595 },
2596 Value::Thing(v) => Some(v),
2598 _ => None,
2600 }
2601 }
2602
2603 pub(crate) fn jsonpath(&self) -> Idiom {
2609 self.to_raw_string()
2610 .as_str()
2611 .trim_start_matches('/')
2612 .split(&['.', '/'][..])
2613 .map(Part::from)
2614 .collect::<Vec<Part>>()
2615 .into()
2616 }
2617
2618 pub(crate) fn is_static(&self) -> bool {
2624 match self {
2625 Value::None => true,
2626 Value::Null => true,
2627 Value::Bool(_) => true,
2628 Value::Bytes(_) => true,
2629 Value::Uuid(_) => true,
2630 Value::Thing(_) => true,
2631 Value::Number(_) => true,
2632 Value::Strand(_) => true,
2633 Value::Duration(_) => true,
2634 Value::Datetime(_) => true,
2635 Value::Geometry(_) => true,
2636 Value::Array(v) => v.is_static(),
2637 Value::Object(v) => v.is_static(),
2638 Value::Expression(v) => v.is_static(),
2639 Value::Function(v) => v.is_static(),
2640 Value::Cast(v) => v.is_static(),
2641 Value::Constant(_) => true,
2642 _ => false,
2643 }
2644 }
2645
2646 pub fn equal(&self, other: &Value) -> bool {
2652 match self {
2653 Value::None => other.is_none(),
2654 Value::Null => other.is_null(),
2655 Value::Bool(v) => match other {
2656 Value::Bool(w) => v == w,
2657 _ => false,
2658 },
2659 Value::Uuid(v) => match other {
2660 Value::Uuid(w) => v == w,
2661 Value::Regex(w) => w.regex().is_match(v.to_raw().as_str()),
2662 _ => false,
2663 },
2664 Value::Thing(v) => match other {
2665 Value::Thing(w) => v == w,
2666 Value::Regex(w) => w.regex().is_match(v.to_raw().as_str()),
2667 _ => false,
2668 },
2669 Value::Strand(v) => match other {
2670 Value::Strand(w) => v == w,
2671 Value::Regex(w) => w.regex().is_match(v.as_str()),
2672 _ => false,
2673 },
2674 Value::Regex(v) => match other {
2675 Value::Regex(w) => v == w,
2676 Value::Uuid(w) => v.regex().is_match(w.to_raw().as_str()),
2677 Value::Thing(w) => v.regex().is_match(w.to_raw().as_str()),
2678 Value::Strand(w) => v.regex().is_match(w.as_str()),
2679 _ => false,
2680 },
2681 Value::Array(v) => match other {
2682 Value::Array(w) => v == w,
2683 _ => false,
2684 },
2685 Value::Object(v) => match other {
2686 Value::Object(w) => v == w,
2687 _ => false,
2688 },
2689 Value::Number(v) => match other {
2690 Value::Number(w) => v == w,
2691 _ => false,
2692 },
2693 Value::Geometry(v) => match other {
2694 Value::Geometry(w) => v == w,
2695 _ => false,
2696 },
2697 Value::Duration(v) => match other {
2698 Value::Duration(w) => v == w,
2699 _ => false,
2700 },
2701 Value::Datetime(v) => match other {
2702 Value::Datetime(w) => v == w,
2703 _ => false,
2704 },
2705 _ => self == other,
2706 }
2707 }
2708
2709 pub fn all_equal(&self, other: &Value) -> bool {
2711 match self {
2712 Value::Array(v) => v.iter().all(|v| v.equal(other)),
2713 _ => self.equal(other),
2714 }
2715 }
2716
2717 pub fn any_equal(&self, other: &Value) -> bool {
2719 match self {
2720 Value::Array(v) => v.iter().any(|v| v.equal(other)),
2721 _ => self.equal(other),
2722 }
2723 }
2724
2725 pub fn fuzzy(&self, other: &Value) -> bool {
2727 match self {
2728 Value::Uuid(v) => match other {
2729 Value::Strand(w) => v.to_raw().as_str().fuzzy_match(w.as_str()),
2730 _ => false,
2731 },
2732 Value::Strand(v) => match other {
2733 Value::Strand(w) => v.as_str().fuzzy_match(w.as_str()),
2734 _ => false,
2735 },
2736 _ => self.equal(other),
2737 }
2738 }
2739
2740 pub fn all_fuzzy(&self, other: &Value) -> bool {
2742 match self {
2743 Value::Array(v) => v.iter().all(|v| v.fuzzy(other)),
2744 _ => self.fuzzy(other),
2745 }
2746 }
2747
2748 pub fn any_fuzzy(&self, other: &Value) -> bool {
2750 match self {
2751 Value::Array(v) => v.iter().any(|v| v.fuzzy(other)),
2752 _ => self.fuzzy(other),
2753 }
2754 }
2755
2756 pub fn contains(&self, other: &Value) -> bool {
2758 match self {
2759 Value::Array(v) => v.iter().any(|v| v.equal(other)),
2760 Value::Uuid(v) => match other {
2761 Value::Strand(w) => v.to_raw().contains(w.as_str()),
2762 _ => false,
2763 },
2764 Value::Strand(v) => match other {
2765 Value::Strand(w) => v.contains(w.as_str()),
2766 _ => false,
2767 },
2768 Value::Geometry(v) => match other {
2769 Value::Geometry(w) => v.contains(w),
2770 _ => false,
2771 },
2772 Value::Object(v) => match other {
2773 Value::Strand(w) => v.0.contains_key(&w.0),
2774 _ => false,
2775 },
2776 Value::Range(r) => {
2777 let beg = match &r.beg {
2778 Bound::Unbounded => true,
2779 Bound::Included(beg) => beg.le(other),
2780 Bound::Excluded(beg) => beg.lt(other),
2781 };
2782
2783 beg && match &r.end {
2784 Bound::Unbounded => true,
2785 Bound::Included(end) => end.ge(other),
2786 Bound::Excluded(end) => end.gt(other),
2787 }
2788 }
2789 _ => false,
2790 }
2791 }
2792
2793 pub fn contains_all(&self, other: &Value) -> bool {
2795 match other {
2796 Value::Array(v) => v.iter().all(|v| match self {
2797 Value::Array(w) => w.iter().any(|w| v.equal(w)),
2798 Value::Geometry(_) => self.contains(v),
2799 _ => false,
2800 }),
2801 _ => false,
2802 }
2803 }
2804
2805 pub fn contains_any(&self, other: &Value) -> bool {
2807 match other {
2808 Value::Array(v) => v.iter().any(|v| match self {
2809 Value::Array(w) => w.iter().any(|w| v.equal(w)),
2810 Value::Geometry(_) => self.contains(v),
2811 _ => false,
2812 }),
2813 _ => false,
2814 }
2815 }
2816
2817 pub fn intersects(&self, other: &Value) -> bool {
2819 match self {
2820 Value::Geometry(v) => match other {
2821 Value::Geometry(w) => v.intersects(w),
2822 _ => false,
2823 },
2824 _ => false,
2825 }
2826 }
2827
2828 pub fn lexical_cmp(&self, other: &Value) -> Option<Ordering> {
2834 match (self, other) {
2835 (Value::Strand(a), Value::Strand(b)) => Some(lexicmp::lexical_cmp(a, b)),
2836 _ => self.partial_cmp(other),
2837 }
2838 }
2839
2840 pub fn natural_cmp(&self, other: &Value) -> Option<Ordering> {
2842 match (self, other) {
2843 (Value::Strand(a), Value::Strand(b)) => Some(lexicmp::natural_cmp(a, b)),
2844 _ => self.partial_cmp(other),
2845 }
2846 }
2847
2848 pub fn natural_lexical_cmp(&self, other: &Value) -> Option<Ordering> {
2850 match (self, other) {
2851 (Value::Strand(a), Value::Strand(b)) => Some(lexicmp::natural_lexical_cmp(a, b)),
2852 _ => self.partial_cmp(other),
2853 }
2854 }
2855
2856 pub fn can_be_range_bound(&self) -> bool {
2857 matches!(
2858 self,
2859 Value::None
2860 | Value::Null
2861 | Value::Array(_)
2862 | Value::Block(_)
2863 | Value::Bool(_)
2864 | Value::Datetime(_)
2865 | Value::Duration(_)
2866 | Value::Geometry(_)
2867 | Value::Number(_)
2868 | Value::Object(_)
2869 | Value::Param(_)
2870 | Value::Strand(_)
2871 | Value::Subquery(_)
2872 | Value::Table(_)
2873 | Value::Uuid(_)
2874 )
2875 }
2876}
2877
2878impl fmt::Display for Value {
2879 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2880 let mut f = Pretty::from(f);
2881 match self {
2882 Value::None => write!(f, "NONE"),
2883 Value::Null => write!(f, "NULL"),
2884 Value::Array(v) => write!(f, "{v}"),
2885 Value::Block(v) => write!(f, "{v}"),
2886 Value::Bool(v) => write!(f, "{v}"),
2887 Value::Bytes(v) => write!(f, "{v}"),
2888 Value::Cast(v) => write!(f, "{v}"),
2889 Value::Constant(v) => write!(f, "{v}"),
2890 Value::Datetime(v) => write!(f, "{v}"),
2891 Value::Duration(v) => write!(f, "{v}"),
2892 Value::Edges(v) => write!(f, "{v}"),
2893 Value::Expression(v) => write!(f, "{v}"),
2894 Value::Function(v) => write!(f, "{v}"),
2895 Value::Model(v) => write!(f, "{v}"),
2896 Value::Future(v) => write!(f, "{v}"),
2897 Value::Geometry(v) => write!(f, "{v}"),
2898 Value::Idiom(v) => write!(f, "{v}"),
2899 Value::Mock(v) => write!(f, "{v}"),
2900 Value::Number(v) => write!(f, "{v}"),
2901 Value::Object(v) => write!(f, "{v}"),
2902 Value::Param(v) => write!(f, "{v}"),
2903 Value::Range(v) => write!(f, "{v}"),
2904 Value::Regex(v) => write!(f, "{v}"),
2905 Value::Strand(v) => write!(f, "{v}"),
2906 Value::Query(v) => write!(f, "{v}"),
2907 Value::Subquery(v) => write!(f, "{v}"),
2908 Value::Table(v) => write!(f, "{v}"),
2909 Value::Thing(v) => write!(f, "{v}"),
2910 Value::Uuid(v) => write!(f, "{v}"),
2911 Value::Closure(v) => write!(f, "{v}"),
2912 Value::Refs(v) => write!(f, "{v}"),
2913 }
2914 }
2915}
2916
2917impl InfoStructure for Value {
2918 fn structure(self) -> Value {
2919 self.to_string().into()
2920 }
2921}
2922
2923impl Value {
2924 pub fn validate_computed(&self) -> Result<(), Error> {
2926 use Value::*;
2927 match self {
2928 None | Null | Bool(_) | Number(_) | Strand(_) | Duration(_) | Datetime(_) | Uuid(_)
2929 | Geometry(_) | Bytes(_) | Thing(_) => Ok(()),
2930 Array(a) => a.validate_computed(),
2931 Object(o) => o.validate_computed(),
2932 Range(r) => r.validate_computed(),
2933 _ => Err(Error::NonComputed),
2934 }
2935 }
2936}
2937
2938impl Value {
2939 pub(crate) fn writeable(&self) -> bool {
2941 match self {
2942 Value::Cast(v) => v.writeable(),
2943 Value::Block(v) => v.writeable(),
2944 Value::Idiom(v) => v.writeable(),
2945 Value::Array(v) => v.iter().any(Value::writeable),
2946 Value::Object(v) => v.iter().any(|(_, v)| v.writeable()),
2947 Value::Function(v) => v.writeable(),
2948 Value::Model(m) => m.args.iter().any(Value::writeable),
2949 Value::Subquery(v) => v.writeable(),
2950 Value::Expression(v) => v.writeable(),
2951 _ => false,
2952 }
2953 }
2954 pub(crate) async fn compute(
2956 &self,
2957 stk: &mut Stk,
2958 ctx: &Context,
2959 opt: &Options,
2960 doc: Option<&CursorDoc>,
2961 ) -> Result<Value, Error> {
2962 match self.compute_unbordered(stk, ctx, opt, doc).await {
2963 Err(Error::Return {
2964 value,
2965 }) => Ok(value),
2966 res => res,
2967 }
2968 }
2969 pub(crate) async fn compute_unbordered(
2971 &self,
2972 stk: &mut Stk,
2973 ctx: &Context,
2974 opt: &Options,
2975 doc: Option<&CursorDoc>,
2976 ) -> Result<Value, Error> {
2977 let opt = &opt.dive(1)?;
2979
2980 match self {
2981 Value::Cast(v) => v.compute(stk, ctx, opt, doc).await,
2982 Value::Thing(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
2983 Value::Block(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
2984 Value::Range(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
2985 Value::Param(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
2986 Value::Idiom(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
2987 Value::Array(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
2988 Value::Object(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
2989 Value::Future(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
2990 Value::Constant(v) => v.compute(),
2991 Value::Function(v) => v.compute(stk, ctx, opt, doc).await,
2992 Value::Model(v) => v.compute(stk, ctx, opt, doc).await,
2993 Value::Subquery(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
2994 Value::Expression(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
2995 Value::Refs(v) => v.compute(ctx, opt, doc).await,
2996 _ => Ok(self.to_owned()),
2997 }
2998 }
2999}
3000
3001pub(crate) trait TryAdd<Rhs = Self> {
3004 type Output;
3005 fn try_add(self, rhs: Rhs) -> Result<Self::Output, Error>;
3006}
3007
3008impl TryAdd for Value {
3009 type Output = Self;
3010 fn try_add(self, other: Self) -> Result<Self, Error> {
3011 Ok(match (self, other) {
3012 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_add(w)?),
3013 (Self::Strand(v), Self::Strand(w)) => Self::Strand(v.try_add(w)?),
3014 (Self::Datetime(v), Self::Duration(w)) => Self::Datetime(w.try_add(v)?),
3015 (Self::Duration(v), Self::Datetime(w)) => Self::Datetime(v.try_add(w)?),
3016 (Self::Duration(v), Self::Duration(w)) => Self::Duration(v.try_add(w)?),
3017 (v, w) => return Err(Error::TryAdd(v.to_raw_string(), w.to_raw_string())),
3018 })
3019 }
3020}
3021
3022pub(crate) trait TrySub<Rhs = Self> {
3025 type Output;
3026 fn try_sub(self, v: Rhs) -> Result<Self::Output, Error>;
3027}
3028
3029impl TrySub for Value {
3030 type Output = Self;
3031 fn try_sub(self, other: Self) -> Result<Self, Error> {
3032 Ok(match (self, other) {
3033 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_sub(w)?),
3034 (Self::Datetime(v), Self::Datetime(w)) => Self::Duration(v.try_sub(w)?),
3035 (Self::Datetime(v), Self::Duration(w)) => Self::Datetime(w.try_sub(v)?),
3036 (Self::Duration(v), Self::Datetime(w)) => Self::Datetime(v.try_sub(w)?),
3037 (Self::Duration(v), Self::Duration(w)) => Self::Duration(v.try_sub(w)?),
3038 (v, w) => return Err(Error::TrySub(v.to_raw_string(), w.to_raw_string())),
3039 })
3040 }
3041}
3042
3043pub(crate) trait TryMul<Rhs = Self> {
3046 type Output;
3047 fn try_mul(self, v: Self) -> Result<Self::Output, Error>;
3048}
3049
3050impl TryMul for Value {
3051 type Output = Self;
3052 fn try_mul(self, other: Self) -> Result<Self, Error> {
3053 Ok(match (self, other) {
3054 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_mul(w)?),
3055 (v, w) => return Err(Error::TryMul(v.to_raw_string(), w.to_raw_string())),
3056 })
3057 }
3058}
3059
3060pub(crate) trait TryDiv<Rhs = Self> {
3063 type Output;
3064 fn try_div(self, v: Self) -> Result<Self::Output, Error>;
3065}
3066
3067impl TryDiv for Value {
3068 type Output = Self;
3069 fn try_div(self, other: Self) -> Result<Self, Error> {
3070 Ok(match (self, other) {
3071 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_div(w)?),
3072 (v, w) => return Err(Error::TryDiv(v.to_raw_string(), w.to_raw_string())),
3073 })
3074 }
3075}
3076
3077pub(crate) trait TryFloatDiv<Rhs = Self> {
3080 type Output;
3081 fn try_float_div(self, v: Self) -> Result<Self::Output, Error>;
3082}
3083
3084impl TryFloatDiv for Value {
3085 type Output = Self;
3086 fn try_float_div(self, other: Self) -> Result<Self::Output, Error> {
3087 Ok(match (self, other) {
3088 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_float_div(w)?),
3089 (v, w) => return Err(Error::TryDiv(v.to_raw_string(), w.to_raw_string())),
3090 })
3091 }
3092}
3093
3094pub(crate) trait TryRem<Rhs = Self> {
3097 type Output;
3098 fn try_rem(self, v: Self) -> Result<Self::Output, Error>;
3099}
3100
3101impl TryRem for Value {
3102 type Output = Self;
3103 fn try_rem(self, other: Self) -> Result<Self, Error> {
3104 Ok(match (self, other) {
3105 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_rem(w)?),
3106 (v, w) => return Err(Error::TryRem(v.to_raw_string(), w.to_raw_string())),
3107 })
3108 }
3109}
3110
3111pub(crate) trait TryPow<Rhs = Self> {
3114 type Output;
3115 fn try_pow(self, v: Self) -> Result<Self::Output, Error>;
3116}
3117
3118impl TryPow for Value {
3119 type Output = Self;
3120 fn try_pow(self, other: Self) -> Result<Self, Error> {
3121 Ok(match (self, other) {
3122 (Value::Number(v), Value::Number(w)) => Self::Number(v.try_pow(w)?),
3123 (v, w) => return Err(Error::TryPow(v.to_raw_string(), w.to_raw_string())),
3124 })
3125 }
3126}
3127
3128pub(crate) trait TryNeg<Rhs = Self> {
3131 type Output;
3132 fn try_neg(self) -> Result<Self::Output, Error>;
3133}
3134
3135impl TryNeg for Value {
3136 type Output = Self;
3137 fn try_neg(self) -> Result<Self, Error> {
3138 Ok(match self {
3139 Self::Number(n) => Self::Number(n.try_neg()?),
3140 v => return Err(Error::TryNeg(v.to_string())),
3141 })
3142 }
3143}
3144
3145#[cfg(test)]
3146mod tests {
3147
3148 use chrono::TimeZone;
3149
3150 use super::*;
3151 use crate::syn::Parse;
3152
3153 #[test]
3154 fn check_none() {
3155 assert!(Value::None.is_none());
3156 assert!(!Value::Null.is_none());
3157 assert!(!Value::from(1).is_none());
3158 }
3159
3160 #[test]
3161 fn check_null() {
3162 assert!(Value::Null.is_null());
3163 assert!(!Value::None.is_null());
3164 assert!(!Value::from(1).is_null());
3165 }
3166
3167 #[test]
3168 fn check_true() {
3169 assert!(!Value::None.is_true());
3170 assert!(Value::Bool(true).is_true());
3171 assert!(!Value::Bool(false).is_true());
3172 assert!(!Value::from(1).is_true());
3173 assert!(!Value::from("something").is_true());
3174 }
3175
3176 #[test]
3177 fn check_false() {
3178 assert!(!Value::None.is_false());
3179 assert!(!Value::Bool(true).is_false());
3180 assert!(Value::Bool(false).is_false());
3181 assert!(!Value::from(1).is_false());
3182 assert!(!Value::from("something").is_false());
3183 }
3184
3185 #[test]
3186 fn convert_truthy() {
3187 assert!(!Value::None.is_truthy());
3188 assert!(!Value::Null.is_truthy());
3189 assert!(Value::Bool(true).is_truthy());
3190 assert!(!Value::Bool(false).is_truthy());
3191 assert!(!Value::from(0).is_truthy());
3192 assert!(Value::from(1).is_truthy());
3193 assert!(Value::from(-1).is_truthy());
3194 assert!(Value::from(1.1).is_truthy());
3195 assert!(Value::from(-1.1).is_truthy());
3196 assert!(Value::from("true").is_truthy());
3197 assert!(Value::from("false").is_truthy());
3198 assert!(Value::from("falsey").is_truthy());
3199 assert!(Value::from("something").is_truthy());
3200 assert!(Value::from(Uuid::new()).is_truthy());
3201 assert!(Value::from(Utc.with_ymd_and_hms(1948, 12, 3, 0, 0, 0).unwrap()).is_truthy());
3202 }
3203
3204 #[test]
3205 fn convert_string() {
3206 assert_eq!(String::from("NONE"), Value::None.as_string());
3207 assert_eq!(String::from("NULL"), Value::Null.as_string());
3208 assert_eq!(String::from("true"), Value::Bool(true).as_string());
3209 assert_eq!(String::from("false"), Value::Bool(false).as_string());
3210 assert_eq!(String::from("0"), Value::from(0).as_string());
3211 assert_eq!(String::from("1"), Value::from(1).as_string());
3212 assert_eq!(String::from("-1"), Value::from(-1).as_string());
3213 assert_eq!(String::from("1.1f"), Value::from(1.1).as_string());
3214 assert_eq!(String::from("-1.1f"), Value::from(-1.1).as_string());
3215 assert_eq!(String::from("3"), Value::from("3").as_string());
3216 assert_eq!(String::from("true"), Value::from("true").as_string());
3217 assert_eq!(String::from("false"), Value::from("false").as_string());
3218 assert_eq!(String::from("something"), Value::from("something").as_string());
3219 }
3220
3221 #[test]
3222 fn check_size() {
3223 assert!(64 >= std::mem::size_of::<Value>(), "size of value too big");
3224 assert!(104 >= std::mem::size_of::<Error>());
3225 assert!(104 >= std::mem::size_of::<Result<Value, Error>>());
3226 assert!(24 >= std::mem::size_of::<crate::sql::number::Number>());
3227 assert!(24 >= std::mem::size_of::<crate::sql::strand::Strand>());
3228 assert!(16 >= std::mem::size_of::<crate::sql::duration::Duration>());
3229 assert!(12 >= std::mem::size_of::<crate::sql::datetime::Datetime>());
3230 assert!(24 >= std::mem::size_of::<crate::sql::array::Array>());
3231 assert!(24 >= std::mem::size_of::<crate::sql::object::Object>());
3232 assert!(48 >= std::mem::size_of::<crate::sql::geometry::Geometry>());
3233 assert!(24 >= std::mem::size_of::<crate::sql::param::Param>());
3234 assert!(24 >= std::mem::size_of::<crate::sql::idiom::Idiom>());
3235 assert!(24 >= std::mem::size_of::<crate::sql::table::Table>());
3236 assert!(56 >= std::mem::size_of::<crate::sql::thing::Thing>());
3237 assert!(40 >= std::mem::size_of::<crate::sql::mock::Mock>());
3238 assert!(32 >= std::mem::size_of::<crate::sql::regex::Regex>());
3239 }
3240
3241 #[test]
3242 fn check_serialize() {
3243 let enc: Vec<u8> = revision::to_vec(&Value::None).unwrap();
3244 assert_eq!(2, enc.len());
3245 let enc: Vec<u8> = revision::to_vec(&Value::Null).unwrap();
3246 assert_eq!(2, enc.len());
3247 let enc: Vec<u8> = revision::to_vec(&Value::Bool(true)).unwrap();
3248 assert_eq!(3, enc.len());
3249 let enc: Vec<u8> = revision::to_vec(&Value::Bool(false)).unwrap();
3250 assert_eq!(3, enc.len());
3251 let enc: Vec<u8> = revision::to_vec(&Value::from("test")).unwrap();
3252 assert_eq!(8, enc.len());
3253 let enc: Vec<u8> = revision::to_vec(&Value::parse("{ hello: 'world' }")).unwrap();
3254 assert_eq!(19, enc.len());
3255 let enc: Vec<u8> = revision::to_vec(&Value::parse("{ compact: true, schema: 0 }")).unwrap();
3256 assert_eq!(27, enc.len());
3257 }
3258
3259 #[test]
3260 fn serialize_deserialize() {
3261 let val = Value::parse(
3262 "{ test: { something: [1, 'two', null, test:tobie, { trueee: false, noneee: nulll }] } }",
3263 );
3264 let res = Value::parse(
3265 "{ test: { something: [1, 'two', null, test:tobie, { trueee: false, noneee: nulll }] } }",
3266 );
3267 let enc: Vec<u8> = revision::to_vec(&val).unwrap();
3268 let dec: Value = revision::from_slice(&enc).unwrap();
3269 assert_eq!(res, dec);
3270 }
3271
3272 #[test]
3273 fn test_value_from_vec_i32() {
3274 let vector: Vec<i32> = vec![1, 2, 3, 4, 5, 6];
3275 let value = Value::from(vector);
3276 assert!(matches!(value, Value::Array(Array(_))));
3277 }
3278
3279 #[test]
3280 fn test_value_from_vec_f32() {
3281 let vector: Vec<f32> = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
3282 let value = Value::from(vector);
3283 assert!(matches!(value, Value::Array(Array(_))));
3284 }
3285}