1#![allow(clippy::derive_ord_xor_partial_ord)]
2
3use crate::ctx::Context;
4use crate::dbs::{Options, Transaction};
5use crate::doc::CursorDoc;
6use crate::err::Error;
7use crate::fnc::util::string::fuzzy::Fuzzy;
8use crate::{
9 array::Uniq,
10 fmt::{Fmt, Pretty},
11 id::{Gen, Id},
12 model::Model,
13 Array, Block, Bytes, Cast, Constant, Datetime, Duration, Edges, Expression, Function, Future,
14 Geometry, Idiom, Kind, Mock, Number, Object, Operation, Param, Part, Query, Range, Regex,
15 Strand, Subquery, Table, Thing, Uuid,
16};
17use async_recursion::async_recursion;
18use chrono::{DateTime, Utc};
19use derive::Store;
20use geo::Point;
21use revision::revisioned;
22use rust_decimal::prelude::*;
23use serde::{Deserialize, Serialize};
24use serde_json::Value as Json;
25use std::cmp::Ordering;
26use std::collections::BTreeMap;
27use std::collections::HashMap;
28use std::fmt::{self, Display, Formatter, Write};
29use std::ops::Deref;
30use std::str::FromStr;
31
32pub(crate) const TOKEN: &str = "$surrealdb::private::crate::Value";
33
34#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Hash)]
35#[revisioned(revision = 1)]
36pub struct Values(pub Vec<Value>);
37
38impl Deref for Values {
39 type Target = Vec<Value>;
40 fn deref(&self) -> &Self::Target {
41 &self.0
42 }
43}
44
45impl IntoIterator for Values {
46 type Item = Value;
47 type IntoIter = std::vec::IntoIter<Self::Item>;
48 fn into_iter(self) -> Self::IntoIter {
49 self.0.into_iter()
50 }
51}
52
53impl Display for Values {
54 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
55 Display::fmt(&Fmt::comma_separated(&self.0), f)
56 }
57}
58
59#[derive(Clone, Debug, Default, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
60#[serde(rename = "$surrealdb::private::crate::Value")]
61#[revisioned(revision = 1)]
62pub enum Value {
63 #[default]
71 None,
72 Null,
73 Bool(bool),
74 Number(Number),
75 Strand(Strand),
76 Duration(Duration),
77 Datetime(Datetime),
78 Uuid(Uuid),
79 Array(Array),
80 Object(Object),
81 Geometry(Geometry),
82 Bytes(Bytes),
83 Thing(Thing),
84 Param(Param),
92 Idiom(Idiom),
93 Table(Table),
94 Mock(Mock),
95 Regex(Regex),
96 Cast(Box<Cast>),
97 Block(Box<Block>),
98 Range(Box<Range>),
99 Edges(Box<Edges>),
100 Future(Box<Future>),
101 Constant(Constant),
102 Function(Box<Function>),
103 Subquery(Box<Subquery>),
104 Expression(Box<Expression>),
105 Query(Query),
106 Model(Box<Model>),
107 }
109
110impl Eq for Value {}
111
112impl Ord for Value {
113 fn cmp(&self, other: &Self) -> Ordering {
114 self.partial_cmp(other).unwrap_or(Ordering::Equal)
115 }
116}
117
118impl From<bool> for Value {
119 #[inline]
120 fn from(v: bool) -> Self {
121 Value::Bool(v)
122 }
123}
124
125impl From<Uuid> for Value {
126 fn from(v: Uuid) -> Self {
127 Value::Uuid(v)
128 }
129}
130
131impl From<Param> for Value {
132 fn from(v: Param) -> Self {
133 Value::Param(v)
134 }
135}
136
137impl From<Idiom> for Value {
138 fn from(v: Idiom) -> Self {
139 Value::Idiom(v)
140 }
141}
142
143impl From<Mock> for Value {
144 fn from(v: Mock) -> Self {
145 Value::Mock(v)
146 }
147}
148
149impl From<Table> for Value {
150 fn from(v: Table) -> Self {
151 Value::Table(v)
152 }
153}
154
155impl From<Thing> for Value {
156 fn from(v: Thing) -> Self {
157 Value::Thing(v)
158 }
159}
160
161impl From<Regex> for Value {
162 fn from(v: Regex) -> Self {
163 Value::Regex(v)
164 }
165}
166
167impl From<Bytes> for Value {
168 fn from(v: Bytes) -> Self {
169 Value::Bytes(v)
170 }
171}
172
173impl From<Array> for Value {
174 fn from(v: Array) -> Self {
175 Value::Array(v)
176 }
177}
178
179impl From<Object> for Value {
180 fn from(v: Object) -> Self {
181 Value::Object(v)
182 }
183}
184
185impl From<Number> for Value {
186 fn from(v: Number) -> Self {
187 Value::Number(v)
188 }
189}
190
191impl From<Strand> for Value {
192 fn from(v: Strand) -> Self {
193 Value::Strand(v)
194 }
195}
196
197impl From<Geometry> for Value {
198 fn from(v: Geometry) -> Self {
199 Value::Geometry(v)
200 }
201}
202
203impl From<Datetime> for Value {
204 fn from(v: Datetime) -> Self {
205 Value::Datetime(v)
206 }
207}
208
209impl From<Duration> for Value {
210 fn from(v: Duration) -> Self {
211 Value::Duration(v)
212 }
213}
214
215impl From<Constant> for Value {
216 fn from(v: Constant) -> Self {
217 Value::Constant(v)
218 }
219}
220
221impl From<Block> for Value {
222 fn from(v: Block) -> Self {
223 Value::Block(Box::new(v))
224 }
225}
226
227impl From<Range> for Value {
228 fn from(v: Range) -> Self {
229 Value::Range(Box::new(v))
230 }
231}
232
233impl From<Edges> for Value {
234 fn from(v: Edges) -> Self {
235 Value::Edges(Box::new(v))
236 }
237}
238
239impl From<Future> for Value {
240 fn from(v: Future) -> Self {
241 Value::Future(Box::new(v))
242 }
243}
244
245impl From<Cast> for Value {
246 fn from(v: Cast) -> Self {
247 Value::Cast(Box::new(v))
248 }
249}
250
251impl From<Function> for Value {
252 fn from(v: Function) -> Self {
253 Value::Function(Box::new(v))
254 }
255}
256
257impl From<Model> for Value {
258 fn from(v: Model) -> Self {
259 Value::Model(Box::new(v))
260 }
261}
262
263impl From<Subquery> for Value {
264 fn from(v: Subquery) -> Self {
265 Value::Subquery(Box::new(v))
266 }
267}
268
269impl From<Expression> for Value {
270 fn from(v: Expression) -> Self {
271 Value::Expression(Box::new(v))
272 }
273}
274
275impl From<Box<Edges>> for Value {
276 fn from(v: Box<Edges>) -> Self {
277 Value::Edges(v)
278 }
279}
280
281impl From<i8> for Value {
282 fn from(v: i8) -> Self {
283 Value::Number(Number::from(v))
284 }
285}
286
287impl From<i16> for Value {
288 fn from(v: i16) -> Self {
289 Value::Number(Number::from(v))
290 }
291}
292
293impl From<i32> for Value {
294 fn from(v: i32) -> Self {
295 Value::Number(Number::from(v))
296 }
297}
298
299impl From<i64> for Value {
300 fn from(v: i64) -> Self {
301 Value::Number(Number::from(v))
302 }
303}
304
305impl From<i128> for Value {
306 fn from(v: i128) -> Self {
307 Value::Number(Number::from(v))
308 }
309}
310
311impl From<isize> for Value {
312 fn from(v: isize) -> Self {
313 Value::Number(Number::from(v))
314 }
315}
316
317impl From<u8> for Value {
318 fn from(v: u8) -> Self {
319 Value::Number(Number::from(v))
320 }
321}
322
323impl From<u16> for Value {
324 fn from(v: u16) -> Self {
325 Value::Number(Number::from(v))
326 }
327}
328
329impl From<u32> for Value {
330 fn from(v: u32) -> Self {
331 Value::Number(Number::from(v))
332 }
333}
334
335impl From<u64> for Value {
336 fn from(v: u64) -> Self {
337 Value::Number(Number::from(v))
338 }
339}
340
341impl From<u128> for Value {
342 fn from(v: u128) -> Self {
343 Value::Number(Number::from(v))
344 }
345}
346
347impl From<usize> for Value {
348 fn from(v: usize) -> Self {
349 Value::Number(Number::from(v))
350 }
351}
352
353impl From<f32> for Value {
354 fn from(v: f32) -> Self {
355 Value::Number(Number::from(v))
356 }
357}
358
359impl From<f64> for Value {
360 fn from(v: f64) -> Self {
361 Value::Number(Number::from(v))
362 }
363}
364
365impl From<Decimal> for Value {
366 fn from(v: Decimal) -> Self {
367 Value::Number(Number::from(v))
368 }
369}
370
371impl From<String> for Value {
372 fn from(v: String) -> Self {
373 Self::Strand(Strand::from(v))
374 }
375}
376
377impl From<&str> for Value {
378 fn from(v: &str) -> Self {
379 Self::Strand(Strand::from(v))
380 }
381}
382
383impl From<DateTime<Utc>> for Value {
384 fn from(v: DateTime<Utc>) -> Self {
385 Value::Datetime(Datetime::from(v))
386 }
387}
388
389impl From<(f64, f64)> for Value {
390 fn from(v: (f64, f64)) -> Self {
391 Value::Geometry(Geometry::from(v))
392 }
393}
394
395impl From<[f64; 2]> for Value {
396 fn from(v: [f64; 2]) -> Self {
397 Value::Geometry(Geometry::from(v))
398 }
399}
400
401impl From<Point<f64>> for Value {
402 fn from(v: Point<f64>) -> Self {
403 Value::Geometry(Geometry::from(v))
404 }
405}
406
407impl From<Operation> for Value {
408 fn from(v: Operation) -> Self {
409 Value::Object(Object::from(v))
410 }
411}
412
413impl From<uuid::Uuid> for Value {
414 fn from(v: uuid::Uuid) -> Self {
415 Value::Uuid(Uuid(v))
416 }
417}
418
419impl From<Vec<&str>> for Value {
420 fn from(v: Vec<&str>) -> Self {
421 Value::Array(Array::from(v))
422 }
423}
424
425impl From<Vec<String>> for Value {
426 fn from(v: Vec<String>) -> Self {
427 Value::Array(Array::from(v))
428 }
429}
430
431impl From<Vec<i32>> for Value {
432 fn from(v: Vec<i32>) -> Self {
433 Value::Array(Array::from(v))
434 }
435}
436
437impl From<Vec<Value>> for Value {
438 fn from(v: Vec<Value>) -> Self {
439 Value::Array(Array::from(v))
440 }
441}
442
443impl From<Vec<Number>> for Value {
444 fn from(v: Vec<Number>) -> Self {
445 Value::Array(Array::from(v))
446 }
447}
448
449impl From<Vec<Operation>> for Value {
450 fn from(v: Vec<Operation>) -> Self {
451 Value::Array(Array::from(v))
452 }
453}
454
455impl From<Vec<bool>> for Value {
456 fn from(v: Vec<bool>) -> Self {
457 Value::Array(Array::from(v))
458 }
459}
460
461impl From<HashMap<&str, Value>> for Value {
462 fn from(v: HashMap<&str, Value>) -> Self {
463 Value::Object(Object::from(v))
464 }
465}
466
467impl From<HashMap<String, Value>> for Value {
468 fn from(v: HashMap<String, Value>) -> Self {
469 Value::Object(Object::from(v))
470 }
471}
472
473impl From<BTreeMap<String, Value>> for Value {
474 fn from(v: BTreeMap<String, Value>) -> Self {
475 Value::Object(Object::from(v))
476 }
477}
478
479impl From<BTreeMap<&str, Value>> for Value {
480 fn from(v: BTreeMap<&str, Value>) -> Self {
481 Value::Object(Object::from(v))
482 }
483}
484
485impl From<Option<Value>> for Value {
486 fn from(v: Option<Value>) -> Self {
487 match v {
488 Some(v) => v,
489 None => Value::None,
490 }
491 }
492}
493
494impl From<Option<String>> for Value {
495 fn from(v: Option<String>) -> Self {
496 match v {
497 Some(v) => Value::from(v),
498 None => Value::None,
499 }
500 }
501}
502
503impl From<Id> for Value {
504 fn from(v: Id) -> Self {
505 match v {
506 Id::Number(v) => v.into(),
507 Id::String(v) => v.into(),
508 Id::Array(v) => v.into(),
509 Id::Object(v) => v.into(),
510 Id::Generate(v) => match v {
511 Gen::Rand => Id::rand().into(),
512 Gen::Ulid => Id::ulid().into(),
513 Gen::Uuid => Id::uuid().into(),
514 },
515 }
516 }
517}
518
519impl From<Query> for Value {
520 fn from(q: Query) -> Self {
521 Value::Query(q)
522 }
523}
524
525impl TryFrom<Value> for i8 {
526 type Error = Error;
527 fn try_from(value: Value) -> Result<Self, Self::Error> {
528 match value {
529 Value::Number(x) => x.try_into(),
530 _ => Err(Error::TryFrom(value.to_string(), "i8")),
531 }
532 }
533}
534
535impl TryFrom<Value> for i16 {
536 type Error = Error;
537 fn try_from(value: Value) -> Result<Self, Self::Error> {
538 match value {
539 Value::Number(x) => x.try_into(),
540 _ => Err(Error::TryFrom(value.to_string(), "i16")),
541 }
542 }
543}
544
545impl TryFrom<Value> for i32 {
546 type Error = Error;
547 fn try_from(value: Value) -> Result<Self, Self::Error> {
548 match value {
549 Value::Number(x) => x.try_into(),
550 _ => Err(Error::TryFrom(value.to_string(), "i32")),
551 }
552 }
553}
554
555impl TryFrom<Value> for i64 {
556 type Error = Error;
557 fn try_from(value: Value) -> Result<Self, Self::Error> {
558 match value {
559 Value::Number(x) => x.try_into(),
560 _ => Err(Error::TryFrom(value.to_string(), "i64")),
561 }
562 }
563}
564
565impl TryFrom<Value> for i128 {
566 type Error = Error;
567 fn try_from(value: Value) -> Result<Self, Self::Error> {
568 match value {
569 Value::Number(x) => x.try_into(),
570 _ => Err(Error::TryFrom(value.to_string(), "i128")),
571 }
572 }
573}
574
575impl TryFrom<Value> for u8 {
576 type Error = Error;
577 fn try_from(value: Value) -> Result<Self, Self::Error> {
578 match value {
579 Value::Number(x) => x.try_into(),
580 _ => Err(Error::TryFrom(value.to_string(), "u8")),
581 }
582 }
583}
584
585impl TryFrom<Value> for u16 {
586 type Error = Error;
587 fn try_from(value: Value) -> Result<Self, Self::Error> {
588 match value {
589 Value::Number(x) => x.try_into(),
590 _ => Err(Error::TryFrom(value.to_string(), "u16")),
591 }
592 }
593}
594
595impl TryFrom<Value> for u32 {
596 type Error = Error;
597 fn try_from(value: Value) -> Result<Self, Self::Error> {
598 match value {
599 Value::Number(x) => x.try_into(),
600 _ => Err(Error::TryFrom(value.to_string(), "u32")),
601 }
602 }
603}
604
605impl TryFrom<Value> for u64 {
606 type Error = Error;
607 fn try_from(value: Value) -> Result<Self, Self::Error> {
608 match value {
609 Value::Number(x) => x.try_into(),
610 _ => Err(Error::TryFrom(value.to_string(), "u64")),
611 }
612 }
613}
614
615impl TryFrom<Value> for u128 {
616 type Error = Error;
617 fn try_from(value: Value) -> Result<Self, Self::Error> {
618 match value {
619 Value::Number(x) => x.try_into(),
620 _ => Err(Error::TryFrom(value.to_string(), "u128")),
621 }
622 }
623}
624
625impl TryFrom<Value> for f32 {
626 type Error = Error;
627 fn try_from(value: Value) -> Result<Self, Self::Error> {
628 match value {
629 Value::Number(x) => x.try_into(),
630 _ => Err(Error::TryFrom(value.to_string(), "f32")),
631 }
632 }
633}
634
635impl TryFrom<Value> for f64 {
636 type Error = Error;
637 fn try_from(value: Value) -> Result<Self, Self::Error> {
638 match value {
639 Value::Number(x) => x.try_into(),
640 _ => Err(Error::TryFrom(value.to_string(), "f64")),
641 }
642 }
643}
644
645impl TryFrom<Value> for Decimal {
646 type Error = Error;
647 fn try_from(value: Value) -> Result<Self, Self::Error> {
648 match value {
649 Value::Number(x) => x.try_into(),
650 _ => Err(Error::TryFrom(value.to_string(), "Decimal")),
651 }
652 }
653}
654
655impl TryFrom<Value> for String {
656 type Error = Error;
657 fn try_from(value: Value) -> Result<Self, Self::Error> {
658 match value {
659 Value::Strand(x) => Ok(x.into()),
660 _ => Err(Error::TryFrom(value.to_string(), "String")),
661 }
662 }
663}
664
665impl TryFrom<Value> for bool {
666 type Error = Error;
667 fn try_from(value: Value) -> Result<Self, Self::Error> {
668 match value {
669 Value::Bool(v) => Ok(v),
670 _ => Err(Error::TryFrom(value.to_string(), "bool")),
671 }
672 }
673}
674
675impl TryFrom<Value> for std::time::Duration {
676 type Error = Error;
677 fn try_from(value: Value) -> Result<Self, Self::Error> {
678 match value {
679 Value::Duration(x) => Ok(x.into()),
680 _ => Err(Error::TryFrom(value.to_string(), "time::Duration")),
681 }
682 }
683}
684
685impl TryFrom<Value> for DateTime<Utc> {
686 type Error = Error;
687 fn try_from(value: Value) -> Result<Self, Self::Error> {
688 match value {
689 Value::Datetime(x) => Ok(x.into()),
690 _ => Err(Error::TryFrom(value.to_string(), "chrono::DateTime<Utc>")),
691 }
692 }
693}
694
695impl TryFrom<Value> for uuid::Uuid {
696 type Error = Error;
697 fn try_from(value: Value) -> Result<Self, Self::Error> {
698 match value {
699 Value::Uuid(x) => Ok(x.into()),
700 _ => Err(Error::TryFrom(value.to_string(), "uuid::Uuid")),
701 }
702 }
703}
704
705impl TryFrom<Value> for Vec<Value> {
706 type Error = Error;
707 fn try_from(value: Value) -> Result<Self, Self::Error> {
708 match value {
709 Value::Array(x) => Ok(x.into()),
710 _ => Err(Error::TryFrom(value.to_string(), "Vec<Value>")),
711 }
712 }
713}
714
715impl TryFrom<Value> for Number {
716 type Error = Error;
717 fn try_from(value: Value) -> Result<Self, Self::Error> {
718 match value {
719 Value::Number(x) => Ok(x),
720 _ => Err(Error::TryFrom(value.to_string(), "Number")),
721 }
722 }
723}
724
725impl TryFrom<Value> for Datetime {
726 type Error = Error;
727 fn try_from(value: Value) -> Result<Self, Self::Error> {
728 match value {
729 Value::Datetime(x) => Ok(x),
730 _ => Err(Error::TryFrom(value.to_string(), "Datetime")),
731 }
732 }
733}
734
735impl TryFrom<Value> for Object {
736 type Error = Error;
737 fn try_from(value: Value) -> Result<Self, Self::Error> {
738 match value {
739 Value::Object(x) => Ok(x),
740 _ => Err(Error::TryFrom(value.to_string(), "Object")),
741 }
742 }
743}
744
745impl FromIterator<Value> for Value {
746 fn from_iter<I: IntoIterator<Item = Value>>(iter: I) -> Self {
747 Value::Array(Array(iter.into_iter().collect()))
748 }
749}
750
751impl FromIterator<(String, Value)> for Value {
752 fn from_iter<I: IntoIterator<Item = (String, Value)>>(iter: I) -> Self {
753 Value::Object(Object(iter.into_iter().collect()))
754 }
755}
756
757impl Value {
758 pub fn base() -> Self {
764 Value::Object(Object::default())
765 }
766
767 pub fn ok(self) -> Result<Value, Error> {
773 Ok(self)
774 }
775
776 pub fn some(self) -> Option<Value> {
778 match self {
779 Value::None => None,
780 val => Some(val),
781 }
782 }
783
784 pub fn is_none_or_null(&self) -> bool {
790 matches!(self, Value::None | Value::Null)
791 }
792
793 pub fn is_none(&self) -> bool {
795 matches!(self, Value::None)
796 }
797
798 pub fn is_null(&self) -> bool {
800 matches!(self, Value::Null)
801 }
802
803 pub fn is_some(&self) -> bool {
805 !self.is_none() && !self.is_null()
806 }
807
808 pub fn is_bool(&self) -> bool {
810 matches!(self, Value::Bool(_))
811 }
812
813 pub fn is_true(&self) -> bool {
815 matches!(self, Value::Bool(true))
816 }
817
818 pub fn is_false(&self) -> bool {
820 matches!(self, Value::Bool(false))
821 }
822
823 pub fn is_truthy(&self) -> bool {
825 match self {
826 Value::Bool(v) => *v,
827 Value::Uuid(_) => true,
828 Value::Thing(_) => true,
829 Value::Geometry(_) => true,
830 Value::Array(v) => !v.is_empty(),
831 Value::Object(v) => !v.is_empty(),
832 Value::Strand(v) => !v.is_empty() && !v.eq_ignore_ascii_case("false"),
833 Value::Number(v) => v.is_truthy(),
834 Value::Duration(v) => v.as_nanos() > 0,
835 Value::Datetime(v) => v.timestamp() > 0,
836 _ => false,
837 }
838 }
839
840 pub fn is_uuid(&self) -> bool {
842 matches!(self, Value::Uuid(_))
843 }
844
845 pub fn is_thing(&self) -> bool {
847 matches!(self, Value::Thing(_))
848 }
849
850 pub fn is_mock(&self) -> bool {
852 matches!(self, Value::Mock(_))
853 }
854
855 pub fn is_param(&self) -> bool {
857 matches!(self, Value::Param(_))
858 }
859
860 pub fn is_range(&self) -> bool {
862 matches!(self, Value::Range(_))
863 }
864
865 pub fn is_table(&self) -> bool {
867 matches!(self, Value::Table(_))
868 }
869
870 pub fn is_strand(&self) -> bool {
872 matches!(self, Value::Strand(_))
873 }
874
875 pub fn is_query(&self) -> bool {
877 matches!(self, Value::Query(_))
878 }
879
880 pub fn is_bytes(&self) -> bool {
882 matches!(self, Value::Bytes(_))
883 }
884
885 pub fn is_array(&self) -> bool {
887 matches!(self, Value::Array(_))
888 }
889
890 pub fn is_object(&self) -> bool {
892 matches!(self, Value::Object(_))
893 }
894
895 pub fn is_number(&self) -> bool {
897 matches!(self, Value::Number(_))
898 }
899
900 pub fn is_datetime(&self) -> bool {
902 matches!(self, Value::Datetime(_))
903 }
904
905 pub fn is_duration(&self) -> bool {
907 matches!(self, Value::Duration(_))
908 }
909
910 pub fn is_record(&self) -> bool {
912 matches!(self, Value::Thing(_))
913 }
914
915 pub fn is_record_of_table(&self, table: String) -> bool {
917 match self {
918 Value::Thing(Thing {
919 tb,
920 ..
921 }) => *tb == table,
922 _ => false,
923 }
924 }
925
926 pub fn is_geometry(&self) -> bool {
928 matches!(self, Value::Geometry(_))
929 }
930
931 pub fn is_int(&self) -> bool {
933 matches!(self, Value::Number(Number::Int(_)))
934 }
935
936 pub fn is_float(&self) -> bool {
938 matches!(self, Value::Number(Number::Float(_)))
939 }
940
941 pub fn is_decimal(&self) -> bool {
943 matches!(self, Value::Number(Number::Decimal(_)))
944 }
945
946 pub fn is_nan(&self) -> bool {
948 matches!(self, Value::Number(v) if v.is_nan())
949 }
950
951 pub fn is_integer(&self) -> bool {
953 matches!(self, Value::Number(v) if v.is_integer())
954 }
955
956 pub fn is_positive(&self) -> bool {
958 matches!(self, Value::Number(v) if v.is_positive())
959 }
960
961 pub fn is_negative(&self) -> bool {
963 matches!(self, Value::Number(v) if v.is_negative())
964 }
965
966 pub fn is_zero_or_positive(&self) -> bool {
968 matches!(self, Value::Number(v) if v.is_zero_or_positive())
969 }
970
971 pub fn is_zero_or_negative(&self) -> bool {
973 matches!(self, Value::Number(v) if v.is_zero_or_negative())
974 }
975
976 pub fn is_record_type(&self, types: &[Table]) -> bool {
978 match self {
979 Value::Thing(v) => types.is_empty() || types.iter().any(|tb| tb.0 == v.tb),
980 _ => false,
981 }
982 }
983
984 pub fn is_geometry_type(&self, types: &[String]) -> bool {
986 match self {
987 Value::Geometry(Geometry::Point(_)) => {
988 types.iter().any(|t| matches!(t.as_str(), "feature" | "point"))
989 }
990 Value::Geometry(Geometry::Line(_)) => {
991 types.iter().any(|t| matches!(t.as_str(), "feature" | "line"))
992 }
993 Value::Geometry(Geometry::Polygon(_)) => {
994 types.iter().any(|t| matches!(t.as_str(), "feature" | "polygon"))
995 }
996 Value::Geometry(Geometry::MultiPoint(_)) => {
997 types.iter().any(|t| matches!(t.as_str(), "feature" | "multipoint"))
998 }
999 Value::Geometry(Geometry::MultiLine(_)) => {
1000 types.iter().any(|t| matches!(t.as_str(), "feature" | "multiline"))
1001 }
1002 Value::Geometry(Geometry::MultiPolygon(_)) => {
1003 types.iter().any(|t| matches!(t.as_str(), "feature" | "multipolygon"))
1004 }
1005 Value::Geometry(Geometry::Collection(_)) => {
1006 types.iter().any(|t| matches!(t.as_str(), "feature" | "collection"))
1007 }
1008 _ => false,
1009 }
1010 }
1011
1012 pub fn as_string(self) -> String {
1018 match self {
1019 Value::Strand(v) => v.0,
1020 Value::Uuid(v) => v.to_raw(),
1021 Value::Datetime(v) => v.to_raw(),
1022 _ => self.to_string(),
1023 }
1024 }
1025
1026 pub fn as_raw_string(self) -> String {
1028 match self {
1029 Value::Strand(v) => v.0,
1030 Value::Uuid(v) => v.to_raw(),
1031 Value::Datetime(v) => v.to_raw(),
1032 _ => self.to_string(),
1033 }
1034 }
1035
1036 pub fn to_raw_string(&self) -> String {
1042 match self {
1043 Value::Strand(v) => v.0.to_owned(),
1044 Value::Uuid(v) => v.to_raw(),
1045 Value::Datetime(v) => v.to_raw(),
1046 _ => self.to_string(),
1047 }
1048 }
1049
1050 pub fn to_idiom(&self) -> Idiom {
1052 match self {
1053 Value::Idiom(v) => v.simplify(),
1054 Value::Param(v) => v.to_raw().into(),
1055 Value::Strand(v) => v.0.to_string().into(),
1056 Value::Datetime(v) => v.0.to_string().into(),
1057 Value::Future(_) => "future".to_string().into(),
1058 Value::Function(v) => v.to_idiom(),
1059 _ => self.to_string().into(),
1060 }
1061 }
1062
1063 pub fn can_start_idiom(&self) -> bool {
1065 match self {
1066 Value::Function(x) => !x.is_script(),
1067 Value::Model(_)
1068 | Value::Subquery(_)
1069 | Value::Constant(_)
1070 | Value::Datetime(_)
1071 | Value::Duration(_)
1072 | Value::Uuid(_)
1073 | Value::Number(_)
1074 | Value::Object(_)
1075 | Value::Array(_)
1076 | Value::Param(_)
1077 | Value::Edges(_)
1078 | Value::Thing(_) => true,
1079 _ => false,
1080 }
1081 }
1082
1083 pub fn to_operations(&self) -> Result<Vec<Operation>, Error> {
1085 match self {
1086 Value::Array(v) => v
1087 .iter()
1088 .map(|v| match v {
1089 Value::Object(v) => v.to_operation(),
1090 _ => Err(Error::InvalidPatch {
1091 message: String::from("Operation must be an object"),
1092 }),
1093 })
1094 .collect::<Result<Vec<_>, Error>>(),
1095 _ => Err(Error::InvalidPatch {
1096 message: String::from("Operations must be an array"),
1097 }),
1098 }
1099 }
1100
1101 pub fn into_json(self) -> Json {
1106 self.into()
1107 }
1108
1109 pub fn could_be_table(self) -> Value {
1115 match self {
1116 Value::Strand(v) => Value::Table(v.0.into()),
1117 _ => self,
1118 }
1119 }
1120
1121 pub fn kindof(&self) -> &'static str {
1127 match self {
1128 Self::None => "none",
1129 Self::Null => "null",
1130 Self::Bool(_) => "bool",
1131 Self::Uuid(_) => "uuid",
1132 Self::Array(_) => "array",
1133 Self::Object(_) => "object",
1134 Self::Strand(_) => "string",
1135 Self::Duration(_) => "duration",
1136 Self::Datetime(_) => "datetime",
1137 Self::Number(Number::Int(_)) => "int",
1138 Self::Number(Number::Float(_)) => "float",
1139 Self::Number(Number::Decimal(_)) => "decimal",
1140 Self::Geometry(Geometry::Point(_)) => "geometry<point>",
1141 Self::Geometry(Geometry::Line(_)) => "geometry<line>",
1142 Self::Geometry(Geometry::Polygon(_)) => "geometry<polygon>",
1143 Self::Geometry(Geometry::MultiPoint(_)) => "geometry<multipoint>",
1144 Self::Geometry(Geometry::MultiLine(_)) => "geometry<multiline>",
1145 Self::Geometry(Geometry::MultiPolygon(_)) => "geometry<multipolygon>",
1146 Self::Geometry(Geometry::Collection(_)) => "geometry<collection>",
1147 Self::Bytes(_) => "bytes",
1148 _ => "incorrect type",
1149 }
1150 }
1151
1152 pub(crate) fn coerce_to(self, kind: &Kind) -> Result<Value, Error> {
1158 let res = match kind {
1160 Kind::Any => Ok(self),
1161 Kind::Null => self.coerce_to_null(),
1162 Kind::Bool => self.coerce_to_bool().map(Value::from),
1163 Kind::Int => self.coerce_to_int().map(Value::from),
1164 Kind::Float => self.coerce_to_float().map(Value::from),
1165 Kind::Decimal => self.coerce_to_decimal().map(Value::from),
1166 Kind::Number => self.coerce_to_number().map(Value::from),
1167 Kind::String => self.coerce_to_strand().map(Value::from),
1168 Kind::Datetime => self.coerce_to_datetime().map(Value::from),
1169 Kind::Duration => self.coerce_to_duration().map(Value::from),
1170 Kind::Object => self.coerce_to_object().map(Value::from),
1171 Kind::Point => self.coerce_to_point().map(Value::from),
1172 Kind::Bytes => self.coerce_to_bytes().map(Value::from),
1173 Kind::Uuid => self.coerce_to_uuid().map(Value::from),
1174 Kind::Set(t, l) => match l {
1175 Some(l) => self.coerce_to_set_type_len(t, l).map(Value::from),
1176 None => self.coerce_to_set_type(t).map(Value::from),
1177 },
1178 Kind::Array(t, l) => match l {
1179 Some(l) => self.coerce_to_array_type_len(t, l).map(Value::from),
1180 None => self.coerce_to_array_type(t).map(Value::from),
1181 },
1182 Kind::Record(t) => match t.is_empty() {
1183 true => self.coerce_to_record().map(Value::from),
1184 false => self.coerce_to_record_type(t).map(Value::from),
1185 },
1186 Kind::Geometry(t) => match t.is_empty() {
1187 true => self.coerce_to_geometry().map(Value::from),
1188 false => self.coerce_to_geometry_type(t).map(Value::from),
1189 },
1190 Kind::Option(k) => match self {
1191 Self::None => Ok(Self::None),
1192 v => v.coerce_to(k),
1193 },
1194 Kind::Either(k) => {
1195 let mut val = self;
1196 for k in k {
1197 match val.coerce_to(k) {
1198 Err(Error::CoerceTo {
1199 from,
1200 ..
1201 }) => val = from,
1202 Err(e) => return Err(e),
1203 Ok(v) => return Ok(v),
1204 }
1205 }
1206 Err(Error::CoerceTo {
1207 from: val,
1208 into: kind.to_string(),
1209 })
1210 }
1211 };
1212 match res {
1214 Err(Error::CoerceTo {
1216 from,
1217 ..
1218 }) => Err(Error::CoerceTo {
1219 from,
1220 into: kind.to_string(),
1221 }),
1222 Err(e) => Err(e),
1224 Ok(v) => Ok(v),
1226 }
1227 }
1228
1229 #[doc(hidden)]
1231 pub fn coerce_to_i64(self) -> Result<i64, Error> {
1232 match self {
1233 Value::Number(Number::Int(v)) => Ok(v),
1235 Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(v as i64),
1237 Value::Number(Number::Decimal(v)) if v.is_integer() => match v.try_into() {
1239 Ok(v) => Ok(v),
1241 _ => Err(Error::CoerceTo {
1243 from: self,
1244 into: "i64".into(),
1245 }),
1246 },
1247 _ => Err(Error::CoerceTo {
1249 from: self,
1250 into: "i64".into(),
1251 }),
1252 }
1253 }
1254
1255 pub(crate) fn coerce_to_u64(self) -> Result<u64, Error> {
1257 match self {
1258 Value::Number(Number::Int(v)) => Ok(v as u64),
1260 Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(v as u64),
1262 Value::Number(Number::Decimal(v)) if v.is_integer() => match v.try_into() {
1264 Ok(v) => Ok(v),
1266 _ => Err(Error::CoerceTo {
1268 from: self,
1269 into: "u64".into(),
1270 }),
1271 },
1272 _ => Err(Error::CoerceTo {
1274 from: self,
1275 into: "u64".into(),
1276 }),
1277 }
1278 }
1279
1280 pub(crate) fn coerce_to_f64(self) -> Result<f64, Error> {
1282 match self {
1283 Value::Number(Number::Float(v)) => Ok(v),
1285 Value::Number(Number::Int(v)) => Ok(v as f64),
1287 Value::Number(Number::Decimal(v)) => match v.try_into() {
1289 Ok(v) => Ok(v),
1291 _ => Err(Error::CoerceTo {
1293 from: self,
1294 into: "f64".into(),
1295 }),
1296 },
1297 _ => Err(Error::CoerceTo {
1299 from: self,
1300 into: "f64".into(),
1301 }),
1302 }
1303 }
1304
1305 pub(crate) fn coerce_to_null(self) -> Result<Value, Error> {
1307 match self {
1308 Value::Null => Ok(Value::Null),
1310 _ => Err(Error::CoerceTo {
1312 from: self,
1313 into: "null".into(),
1314 }),
1315 }
1316 }
1317
1318 pub(crate) fn coerce_to_bool(self) -> Result<bool, Error> {
1320 match self {
1321 Value::Bool(v) => Ok(v),
1323 _ => Err(Error::CoerceTo {
1325 from: self,
1326 into: "bool".into(),
1327 }),
1328 }
1329 }
1330
1331 pub(crate) fn coerce_to_int(self) -> Result<Number, Error> {
1333 match self {
1334 Value::Number(v) if v.is_int() => Ok(v),
1336 Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(Number::Int(v as i64)),
1338 Value::Number(Number::Decimal(v)) if v.is_integer() => match v.to_i64() {
1340 Some(v) => Ok(Number::Int(v)),
1342 _ => Err(Error::CoerceTo {
1344 from: self,
1345 into: "int".into(),
1346 }),
1347 },
1348 _ => Err(Error::CoerceTo {
1350 from: self,
1351 into: "int".into(),
1352 }),
1353 }
1354 }
1355
1356 pub(crate) fn coerce_to_float(self) -> Result<Number, Error> {
1358 match self {
1359 Value::Number(v) if v.is_float() => Ok(v),
1361 Value::Number(Number::Int(v)) => Ok(Number::Float(v as f64)),
1363 Value::Number(Number::Decimal(ref v)) => match v.to_f64() {
1365 Some(v) => Ok(Number::Float(v)),
1367 None => Err(Error::CoerceTo {
1369 from: self,
1370 into: "float".into(),
1371 }),
1372 },
1373 _ => Err(Error::CoerceTo {
1375 from: self,
1376 into: "float".into(),
1377 }),
1378 }
1379 }
1380
1381 pub(crate) fn coerce_to_decimal(self) -> Result<Number, Error> {
1383 match self {
1384 Value::Number(v) if v.is_decimal() => Ok(v),
1386 Value::Number(Number::Int(v)) => match Decimal::from_i64(v) {
1388 Some(v) => Ok(Number::Decimal(v)),
1390 None => Err(Error::CoerceTo {
1392 from: self,
1393 into: "decimal".into(),
1394 }),
1395 },
1396 Value::Number(Number::Float(v)) => match Decimal::from_f64(v) {
1398 Some(v) => Ok(Number::Decimal(v)),
1400 None => Err(Error::CoerceTo {
1402 from: self,
1403 into: "decimal".into(),
1404 }),
1405 },
1406 _ => Err(Error::CoerceTo {
1408 from: self,
1409 into: "decimal".into(),
1410 }),
1411 }
1412 }
1413
1414 pub(crate) fn coerce_to_number(self) -> Result<Number, Error> {
1416 match self {
1417 Value::Number(v) => Ok(v),
1419 _ => Err(Error::CoerceTo {
1421 from: self,
1422 into: "number".into(),
1423 }),
1424 }
1425 }
1426
1427 pub(crate) fn coerce_to_regex(self) -> Result<Regex, Error> {
1429 match self {
1430 Value::Regex(v) => Ok(v),
1432 Value::Strand(v) => Ok(v.as_str().parse()?),
1434 _ => Err(Error::CoerceTo {
1436 from: self,
1437 into: "regex".into(),
1438 }),
1439 }
1440 }
1441
1442 pub(crate) fn coerce_to_string(self) -> Result<String, Error> {
1444 match self {
1445 Value::Uuid(v) => Ok(v.to_raw()),
1447 Value::Datetime(v) => Ok(v.to_raw()),
1449 Value::Strand(v) => Ok(v.as_string()),
1451 _ => Err(Error::CoerceTo {
1453 from: self,
1454 into: "string".into(),
1455 }),
1456 }
1457 }
1458
1459 pub(crate) fn coerce_to_strand(self) -> Result<Strand, Error> {
1461 match self {
1462 Value::Uuid(v) => Ok(v.to_raw().into()),
1464 Value::Datetime(v) => Ok(v.to_raw().into()),
1466 Value::Strand(v) => Ok(v),
1468 _ => Err(Error::CoerceTo {
1470 from: self,
1471 into: "string".into(),
1472 }),
1473 }
1474 }
1475
1476 pub(crate) fn coerce_to_uuid(self) -> Result<Uuid, Error> {
1478 match self {
1479 Value::Uuid(v) => Ok(v),
1481 _ => Err(Error::CoerceTo {
1483 from: self,
1484 into: "uuid".into(),
1485 }),
1486 }
1487 }
1488
1489 pub(crate) fn coerce_to_datetime(self) -> Result<Datetime, Error> {
1491 match self {
1492 Value::Datetime(v) => Ok(v),
1494 _ => Err(Error::CoerceTo {
1496 from: self,
1497 into: "datetime".into(),
1498 }),
1499 }
1500 }
1501
1502 pub(crate) fn coerce_to_duration(self) -> Result<Duration, Error> {
1504 match self {
1505 Value::Duration(v) => Ok(v),
1507 _ => Err(Error::CoerceTo {
1509 from: self,
1510 into: "duration".into(),
1511 }),
1512 }
1513 }
1514
1515 pub(crate) fn coerce_to_bytes(self) -> Result<Bytes, Error> {
1517 match self {
1518 Value::Bytes(v) => Ok(v),
1520 _ => Err(Error::CoerceTo {
1522 from: self,
1523 into: "bytes".into(),
1524 }),
1525 }
1526 }
1527
1528 pub(crate) fn coerce_to_object(self) -> Result<Object, Error> {
1530 match self {
1531 Value::Object(v) => Ok(v),
1533 _ => Err(Error::CoerceTo {
1535 from: self,
1536 into: "object".into(),
1537 }),
1538 }
1539 }
1540
1541 pub(crate) fn coerce_to_array(self) -> Result<Array, Error> {
1543 match self {
1544 Value::Array(v) => Ok(v),
1546 _ => Err(Error::CoerceTo {
1548 from: self,
1549 into: "array".into(),
1550 }),
1551 }
1552 }
1553
1554 pub(crate) fn coerce_to_point(self) -> Result<Geometry, Error> {
1556 match self {
1557 Value::Geometry(Geometry::Point(v)) => Ok(v.into()),
1559 _ => Err(Error::CoerceTo {
1561 from: self,
1562 into: "point".into(),
1563 }),
1564 }
1565 }
1566
1567 pub(crate) fn coerce_to_record(self) -> Result<Thing, Error> {
1569 match self {
1570 Value::Thing(v) => Ok(v),
1572 _ => Err(Error::CoerceTo {
1574 from: self,
1575 into: "record".into(),
1576 }),
1577 }
1578 }
1579
1580 pub(crate) fn coerce_to_geometry(self) -> Result<Geometry, Error> {
1582 match self {
1583 Value::Geometry(v) => Ok(v),
1585 _ => Err(Error::CoerceTo {
1587 from: self,
1588 into: "geometry".into(),
1589 }),
1590 }
1591 }
1592
1593 pub(crate) fn coerce_to_record_type(self, val: &[Table]) -> Result<Thing, Error> {
1595 match self {
1596 Value::Thing(v) if self.is_record_type(val) => Ok(v),
1598 _ => Err(Error::CoerceTo {
1600 from: self,
1601 into: "record".into(),
1602 }),
1603 }
1604 }
1605
1606 pub(crate) fn coerce_to_geometry_type(self, val: &[String]) -> Result<Geometry, Error> {
1608 match self {
1609 Value::Geometry(v) if self.is_geometry_type(val) => Ok(v),
1611 _ => Err(Error::CoerceTo {
1613 from: self,
1614 into: "geometry".into(),
1615 }),
1616 }
1617 }
1618
1619 pub(crate) fn coerce_to_array_type(self, kind: &Kind) -> Result<Array, Error> {
1621 self.coerce_to_array()?
1622 .into_iter()
1623 .map(|value| value.coerce_to(kind))
1624 .collect::<Result<Array, Error>>()
1625 .map_err(|e| match e {
1626 Error::CoerceTo {
1627 from,
1628 ..
1629 } => Error::CoerceTo {
1630 from,
1631 into: format!("array<{kind}>"),
1632 },
1633 e => e,
1634 })
1635 }
1636
1637 pub(crate) fn coerce_to_array_type_len(self, kind: &Kind, len: &u64) -> Result<Array, Error> {
1639 self.coerce_to_array()?
1640 .into_iter()
1641 .map(|value| value.coerce_to(kind))
1642 .collect::<Result<Array, Error>>()
1643 .map_err(|e| match e {
1644 Error::CoerceTo {
1645 from,
1646 ..
1647 } => Error::CoerceTo {
1648 from,
1649 into: format!("array<{kind}, {len}>"),
1650 },
1651 e => e,
1652 })
1653 .and_then(|v| match v.len() {
1654 v if v > *len as usize => Err(Error::LengthInvalid {
1655 kind: format!("array<{kind}, {len}>"),
1656 size: v,
1657 }),
1658 _ => Ok(v),
1659 })
1660 }
1661
1662 pub(crate) fn coerce_to_set_type(self, kind: &Kind) -> Result<Array, Error> {
1664 self.coerce_to_array()?
1665 .uniq()
1666 .into_iter()
1667 .map(|value| value.coerce_to(kind))
1668 .collect::<Result<Array, Error>>()
1669 .map_err(|e| match e {
1670 Error::CoerceTo {
1671 from,
1672 ..
1673 } => Error::CoerceTo {
1674 from,
1675 into: format!("set<{kind}>"),
1676 },
1677 e => e,
1678 })
1679 }
1680
1681 pub(crate) fn coerce_to_set_type_len(self, kind: &Kind, len: &u64) -> Result<Array, Error> {
1683 self.coerce_to_array()?
1684 .uniq()
1685 .into_iter()
1686 .map(|value| value.coerce_to(kind))
1687 .collect::<Result<Array, Error>>()
1688 .map_err(|e| match e {
1689 Error::CoerceTo {
1690 from,
1691 ..
1692 } => Error::CoerceTo {
1693 from,
1694 into: format!("set<{kind}, {len}>"),
1695 },
1696 e => e,
1697 })
1698 .and_then(|v| match v.len() {
1699 v if v > *len as usize => Err(Error::LengthInvalid {
1700 kind: format!("set<{kind}, {len}>"),
1701 size: v,
1702 }),
1703 _ => Ok(v),
1704 })
1705 }
1706
1707 pub(crate) fn convert_to(self, kind: &Kind) -> Result<Value, Error> {
1713 let res = match kind {
1715 Kind::Any => Ok(self),
1716 Kind::Null => self.convert_to_null(),
1717 Kind::Bool => self.convert_to_bool().map(Value::from),
1718 Kind::Int => self.convert_to_int().map(Value::from),
1719 Kind::Float => self.convert_to_float().map(Value::from),
1720 Kind::Decimal => self.convert_to_decimal().map(Value::from),
1721 Kind::Number => self.convert_to_number().map(Value::from),
1722 Kind::String => self.convert_to_strand().map(Value::from),
1723 Kind::Datetime => self.convert_to_datetime().map(Value::from),
1724 Kind::Duration => self.convert_to_duration().map(Value::from),
1725 Kind::Object => self.convert_to_object().map(Value::from),
1726 Kind::Point => self.convert_to_point().map(Value::from),
1727 Kind::Bytes => self.convert_to_bytes().map(Value::from),
1728 Kind::Uuid => self.convert_to_uuid().map(Value::from),
1729 Kind::Set(t, l) => match l {
1730 Some(l) => self.convert_to_set_type_len(t, l).map(Value::from),
1731 None => self.convert_to_set_type(t).map(Value::from),
1732 },
1733 Kind::Array(t, l) => match l {
1734 Some(l) => self.convert_to_array_type_len(t, l).map(Value::from),
1735 None => self.convert_to_array_type(t).map(Value::from),
1736 },
1737 Kind::Record(t) => match t.is_empty() {
1738 true => self.convert_to_record().map(Value::from),
1739 false => self.convert_to_record_type(t).map(Value::from),
1740 },
1741 Kind::Geometry(t) => match t.is_empty() {
1742 true => self.convert_to_geometry().map(Value::from),
1743 false => self.convert_to_geometry_type(t).map(Value::from),
1744 },
1745 Kind::Option(k) => match self {
1746 Self::None => Ok(Self::None),
1747 v => v.convert_to(k),
1748 },
1749 Kind::Either(k) => {
1750 let mut val = self;
1751 for k in k {
1752 match val.convert_to(k) {
1753 Err(Error::ConvertTo {
1754 from,
1755 ..
1756 }) => val = from,
1757 Err(e) => return Err(e),
1758 Ok(v) => return Ok(v),
1759 }
1760 }
1761 Err(Error::ConvertTo {
1762 from: val,
1763 into: kind.to_string(),
1764 })
1765 }
1766 };
1767 match res {
1769 Err(Error::ConvertTo {
1771 from,
1772 ..
1773 }) => Err(Error::ConvertTo {
1774 from,
1775 into: kind.to_string(),
1776 }),
1777 Err(e) => Err(e),
1779 Ok(v) => Ok(v),
1781 }
1782 }
1783
1784 pub(crate) fn convert_to_null(self) -> Result<Value, Error> {
1786 match self {
1787 Value::Null => Ok(Value::Null),
1789 _ => Err(Error::ConvertTo {
1791 from: self,
1792 into: "null".into(),
1793 }),
1794 }
1795 }
1796
1797 pub(crate) fn convert_to_bool(self) -> Result<bool, Error> {
1799 match self {
1800 Value::Bool(v) => Ok(v),
1802 Value::Strand(ref v) => match v.parse::<bool>() {
1804 Ok(v) => Ok(v),
1806 _ => Err(Error::ConvertTo {
1808 from: self,
1809 into: "bool".into(),
1810 }),
1811 },
1812 _ => Err(Error::ConvertTo {
1814 from: self,
1815 into: "bool".into(),
1816 }),
1817 }
1818 }
1819
1820 pub(crate) fn convert_to_int(self) -> Result<Number, Error> {
1822 match self {
1823 Value::Number(v) if v.is_int() => Ok(v),
1825 Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(Number::Int(v as i64)),
1827 Value::Number(Number::Decimal(v)) if v.is_integer() => match v.try_into() {
1829 Ok(v) => Ok(Number::Int(v)),
1831 _ => Err(Error::ConvertTo {
1833 from: self,
1834 into: "int".into(),
1835 }),
1836 },
1837 Value::Strand(ref v) => match v.parse::<i64>() {
1839 Ok(v) => Ok(Number::Int(v)),
1841 _ => Err(Error::ConvertTo {
1843 from: self,
1844 into: "int".into(),
1845 }),
1846 },
1847 _ => Err(Error::ConvertTo {
1849 from: self,
1850 into: "int".into(),
1851 }),
1852 }
1853 }
1854
1855 pub(crate) fn convert_to_float(self) -> Result<Number, Error> {
1857 match self {
1858 Value::Number(v) if v.is_float() => Ok(v),
1860 Value::Number(Number::Int(v)) => Ok(Number::Float(v as f64)),
1862 Value::Number(Number::Decimal(v)) => match v.try_into() {
1864 Ok(v) => Ok(Number::Float(v)),
1866 _ => Err(Error::ConvertTo {
1868 from: self,
1869 into: "float".into(),
1870 }),
1871 },
1872 Value::Strand(ref v) => match v.parse::<f64>() {
1874 Ok(v) => Ok(Number::Float(v)),
1876 _ => Err(Error::ConvertTo {
1878 from: self,
1879 into: "float".into(),
1880 }),
1881 },
1882 _ => Err(Error::ConvertTo {
1884 from: self,
1885 into: "float".into(),
1886 }),
1887 }
1888 }
1889
1890 pub(crate) fn convert_to_decimal(self) -> Result<Number, Error> {
1892 match self {
1893 Value::Number(v) if v.is_decimal() => Ok(v),
1895 #[allow(warnings)]
1899 Value::Number(Number::Int(ref v)) => match Decimal::try_from(*v) {
1900 Ok(v) => Ok(Number::Decimal(v)),
1902 _ => Err(Error::ConvertTo {
1904 from: self,
1905 into: "decimal".into(),
1906 }),
1907 },
1908 Value::Number(Number::Float(ref v)) => match Decimal::try_from(*v) {
1910 Ok(v) => Ok(Number::Decimal(v)),
1912 _ => Err(Error::ConvertTo {
1914 from: self,
1915 into: "decimal".into(),
1916 }),
1917 },
1918 Value::Strand(ref v) => match Decimal::from_str(v) {
1920 Ok(v) => Ok(Number::Decimal(v)),
1922 _ => Err(Error::ConvertTo {
1924 from: self,
1925 into: "decimal".into(),
1926 }),
1927 },
1928 _ => Err(Error::ConvertTo {
1930 from: self,
1931 into: "decimal".into(),
1932 }),
1933 }
1934 }
1935
1936 pub(crate) fn convert_to_number(self) -> Result<Number, Error> {
1938 match self {
1939 Value::Number(v) => Ok(v),
1941 Value::Strand(ref v) => match Number::from_str(v) {
1943 Ok(v) => Ok(v),
1945 _ => Err(Error::ConvertTo {
1947 from: self,
1948 into: "number".into(),
1949 }),
1950 },
1951 _ => Err(Error::ConvertTo {
1953 from: self,
1954 into: "number".into(),
1955 }),
1956 }
1957 }
1958
1959 #[doc(hidden)]
1961 pub fn convert_to_string(self) -> Result<String, Error> {
1962 match self {
1963 Value::Bytes(_) => Err(Error::ConvertTo {
1965 from: self,
1966 into: "string".into(),
1967 }),
1968 Value::None => Err(Error::ConvertTo {
1970 from: self,
1971 into: "string".into(),
1972 }),
1973 Value::Null => Err(Error::ConvertTo {
1975 from: self,
1976 into: "string".into(),
1977 }),
1978 _ => Ok(self.as_string()),
1980 }
1981 }
1982
1983 pub(crate) fn convert_to_strand(self) -> Result<Strand, Error> {
1985 match self {
1986 Value::Bytes(_) => Err(Error::ConvertTo {
1988 from: self,
1989 into: "string".into(),
1990 }),
1991 Value::None => Err(Error::ConvertTo {
1993 from: self,
1994 into: "string".into(),
1995 }),
1996 Value::Null => Err(Error::ConvertTo {
1998 from: self,
1999 into: "string".into(),
2000 }),
2001 Value::Strand(v) => Ok(v),
2003 Value::Uuid(v) => Ok(v.to_raw().into()),
2005 Value::Datetime(v) => Ok(v.to_raw().into()),
2007 _ => Ok(self.to_string().into()),
2009 }
2010 }
2011
2012 pub(crate) fn convert_to_uuid(self) -> Result<Uuid, Error> {
2014 match self {
2015 Value::Uuid(v) => Ok(v),
2017 Value::Strand(ref v) => match Uuid::try_from(v.as_str()) {
2019 Ok(v) => Ok(v),
2021 Err(_) => Err(Error::ConvertTo {
2023 from: self,
2024 into: "uuid".into(),
2025 }),
2026 },
2027 _ => Err(Error::ConvertTo {
2029 from: self,
2030 into: "uuid".into(),
2031 }),
2032 }
2033 }
2034
2035 pub(crate) fn convert_to_datetime(self) -> Result<Datetime, Error> {
2037 match self {
2038 Value::Datetime(v) => Ok(v),
2040 Value::Strand(ref v) => match Datetime::try_from(v.as_str()) {
2042 Ok(v) => Ok(v),
2044 Err(_) => Err(Error::ConvertTo {
2046 from: self,
2047 into: "datetime".into(),
2048 }),
2049 },
2050 _ => Err(Error::ConvertTo {
2052 from: self,
2053 into: "datetime".into(),
2054 }),
2055 }
2056 }
2057
2058 pub(crate) fn convert_to_duration(self) -> Result<Duration, Error> {
2060 match self {
2061 Value::Duration(v) => Ok(v),
2063 Value::Strand(ref v) => match Duration::try_from(v.as_str()) {
2065 Ok(v) => Ok(v),
2067 Err(_) => Err(Error::ConvertTo {
2069 from: self,
2070 into: "duration".into(),
2071 }),
2072 },
2073 _ => Err(Error::ConvertTo {
2075 from: self,
2076 into: "duration".into(),
2077 }),
2078 }
2079 }
2080
2081 pub(crate) fn convert_to_bytes(self) -> Result<Bytes, Error> {
2083 match self {
2084 Value::Bytes(v) => Ok(v),
2086 Value::Strand(s) => Ok(Bytes(s.0.into_bytes())),
2088 _ => Err(Error::ConvertTo {
2090 from: self,
2091 into: "bytes".into(),
2092 }),
2093 }
2094 }
2095
2096 pub(crate) fn convert_to_object(self) -> Result<Object, Error> {
2098 match self {
2099 Value::Object(v) => Ok(v),
2101 _ => Err(Error::ConvertTo {
2103 from: self,
2104 into: "object".into(),
2105 }),
2106 }
2107 }
2108
2109 pub(crate) fn convert_to_array(self) -> Result<Array, Error> {
2111 match self {
2112 Value::Array(v) => Ok(v),
2114 _ => Err(Error::ConvertTo {
2116 from: self,
2117 into: "array".into(),
2118 }),
2119 }
2120 }
2121
2122 pub(crate) fn convert_to_point(self) -> Result<Geometry, Error> {
2124 match self {
2125 Value::Geometry(Geometry::Point(v)) => Ok(v.into()),
2127 Value::Array(ref v) if v.len() == 2 => match v.as_slice() {
2129 [Value::Number(v), Value::Number(w)] => Ok((v.to_float(), w.to_float()).into()),
2131 _ => Err(Error::ConvertTo {
2133 from: self,
2134 into: "point".into(),
2135 }),
2136 },
2137 _ => Err(Error::ConvertTo {
2139 from: self,
2140 into: "point".into(),
2141 }),
2142 }
2143 }
2144
2145 pub(crate) fn convert_to_record(self) -> Result<Thing, Error> {
2147 match self {
2148 Value::Thing(v) => Ok(v),
2150 Value::Strand(v) => Thing::try_from(v.as_str()).map_err(move |_| Error::ConvertTo {
2151 from: Value::Strand(v),
2152 into: "record".into(),
2153 }),
2154 _ => Err(Error::ConvertTo {
2156 from: self,
2157 into: "record".into(),
2158 }),
2159 }
2160 }
2161
2162 pub(crate) fn convert_to_geometry(self) -> Result<Geometry, Error> {
2164 match self {
2165 Value::Geometry(v) => Ok(v),
2167 _ => Err(Error::ConvertTo {
2169 from: self,
2170 into: "geometry".into(),
2171 }),
2172 }
2173 }
2174
2175 pub(crate) fn convert_to_record_type(self, val: &[Table]) -> Result<Thing, Error> {
2177 match self {
2178 Value::Thing(v) if self.is_record_type(val) => Ok(v),
2180 _ => Err(Error::ConvertTo {
2182 from: self,
2183 into: "record".into(),
2184 }),
2185 }
2186 }
2187
2188 pub(crate) fn convert_to_geometry_type(self, val: &[String]) -> Result<Geometry, Error> {
2190 match self {
2191 Value::Geometry(v) if self.is_geometry_type(val) => Ok(v),
2193 _ => Err(Error::ConvertTo {
2195 from: self,
2196 into: "geometry".into(),
2197 }),
2198 }
2199 }
2200
2201 pub(crate) fn convert_to_array_type(self, kind: &Kind) -> Result<Array, Error> {
2203 self.convert_to_array()?
2204 .into_iter()
2205 .map(|value| value.convert_to(kind))
2206 .collect::<Result<Array, Error>>()
2207 .map_err(|e| match e {
2208 Error::ConvertTo {
2209 from,
2210 ..
2211 } => Error::ConvertTo {
2212 from,
2213 into: format!("array<{kind}>"),
2214 },
2215 e => e,
2216 })
2217 }
2218
2219 pub(crate) fn convert_to_array_type_len(self, kind: &Kind, len: &u64) -> Result<Array, Error> {
2221 self.convert_to_array()?
2222 .into_iter()
2223 .map(|value| value.convert_to(kind))
2224 .collect::<Result<Array, Error>>()
2225 .map_err(|e| match e {
2226 Error::ConvertTo {
2227 from,
2228 ..
2229 } => Error::ConvertTo {
2230 from,
2231 into: format!("array<{kind}, {len}>"),
2232 },
2233 e => e,
2234 })
2235 .and_then(|v| match v.len() {
2236 v if v > *len as usize => Err(Error::LengthInvalid {
2237 kind: format!("array<{kind}, {len}>"),
2238 size: v,
2239 }),
2240 _ => Ok(v),
2241 })
2242 }
2243
2244 pub(crate) fn convert_to_set_type(self, kind: &Kind) -> Result<Array, Error> {
2246 self.convert_to_array()?
2247 .uniq()
2248 .into_iter()
2249 .map(|value| value.convert_to(kind))
2250 .collect::<Result<Array, Error>>()
2251 .map_err(|e| match e {
2252 Error::ConvertTo {
2253 from,
2254 ..
2255 } => Error::ConvertTo {
2256 from,
2257 into: format!("set<{kind}>"),
2258 },
2259 e => e,
2260 })
2261 }
2262
2263 pub(crate) fn convert_to_set_type_len(self, kind: &Kind, len: &u64) -> Result<Array, Error> {
2265 self.convert_to_array()?
2266 .uniq()
2267 .into_iter()
2268 .map(|value| value.convert_to(kind))
2269 .collect::<Result<Array, Error>>()
2270 .map_err(|e| match e {
2271 Error::ConvertTo {
2272 from,
2273 ..
2274 } => Error::ConvertTo {
2275 from,
2276 into: format!("set<{kind}, {len}>"),
2277 },
2278 e => e,
2279 })
2280 .and_then(|v| match v.len() {
2281 v if v > *len as usize => Err(Error::LengthInvalid {
2282 kind: format!("set<{kind}, {len}>"),
2283 size: v,
2284 }),
2285 _ => Ok(v),
2286 })
2287 }
2288
2289 pub fn record(self) -> Option<Thing> {
2295 match self {
2296 Value::Object(mut v) => match v.remove("id") {
2298 Some(Value::Thing(v)) => Some(v),
2299 _ => None,
2300 },
2301 Value::Array(mut v) => match v.len() {
2303 1 => v.remove(0).record(),
2304 _ => None,
2305 },
2306 Value::Thing(v) => Some(v),
2308 _ => None,
2310 }
2311 }
2312
2313 pub(crate) fn jsonpath(&self) -> Idiom {
2319 self.to_raw_string()
2320 .as_str()
2321 .trim_start_matches('/')
2322 .split(&['.', '/'][..])
2323 .map(Part::from)
2324 .collect::<Vec<Part>>()
2325 .into()
2326 }
2327
2328 pub(crate) fn is_static(&self) -> bool {
2334 match self {
2335 Value::None => true,
2336 Value::Null => true,
2337 Value::Bool(_) => true,
2338 Value::Bytes(_) => true,
2339 Value::Uuid(_) => true,
2340 Value::Number(_) => true,
2341 Value::Strand(_) => true,
2342 Value::Duration(_) => true,
2343 Value::Datetime(_) => true,
2344 Value::Geometry(_) => true,
2345 Value::Array(v) => v.is_static(),
2346 Value::Object(v) => v.is_static(),
2347 Value::Expression(v) => v.is_static(),
2348 Value::Function(v) => v.is_static(),
2349 Value::Constant(_) => true,
2350 _ => false,
2351 }
2352 }
2353
2354 pub fn equal(&self, other: &Value) -> bool {
2360 match self {
2361 Value::None => other.is_none(),
2362 Value::Null => other.is_null(),
2363 Value::Bool(v) => match other {
2364 Value::Bool(w) => v == w,
2365 _ => false,
2366 },
2367 Value::Uuid(v) => match other {
2368 Value::Uuid(w) => v == w,
2369 Value::Regex(w) => w.regex().is_match(v.to_raw().as_str()),
2370 _ => false,
2371 },
2372 Value::Thing(v) => match other {
2373 Value::Thing(w) => v == w,
2374 Value::Regex(w) => w.regex().is_match(v.to_raw().as_str()),
2375 _ => false,
2376 },
2377 Value::Strand(v) => match other {
2378 Value::Strand(w) => v == w,
2379 Value::Regex(w) => w.regex().is_match(v.as_str()),
2380 _ => false,
2381 },
2382 Value::Regex(v) => match other {
2383 Value::Regex(w) => v == w,
2384 Value::Uuid(w) => v.regex().is_match(w.to_raw().as_str()),
2385 Value::Thing(w) => v.regex().is_match(w.to_raw().as_str()),
2386 Value::Strand(w) => v.regex().is_match(w.as_str()),
2387 _ => false,
2388 },
2389 Value::Array(v) => match other {
2390 Value::Array(w) => v == w,
2391 _ => false,
2392 },
2393 Value::Object(v) => match other {
2394 Value::Object(w) => v == w,
2395 _ => false,
2396 },
2397 Value::Number(v) => match other {
2398 Value::Number(w) => v == w,
2399 _ => false,
2400 },
2401 Value::Geometry(v) => match other {
2402 Value::Geometry(w) => v == w,
2403 _ => false,
2404 },
2405 Value::Duration(v) => match other {
2406 Value::Duration(w) => v == w,
2407 _ => false,
2408 },
2409 Value::Datetime(v) => match other {
2410 Value::Datetime(w) => v == w,
2411 _ => false,
2412 },
2413 _ => self == other,
2414 }
2415 }
2416
2417 pub fn all_equal(&self, other: &Value) -> bool {
2419 match self {
2420 Value::Array(v) => v.iter().all(|v| v.equal(other)),
2421 _ => self.equal(other),
2422 }
2423 }
2424
2425 pub fn any_equal(&self, other: &Value) -> bool {
2427 match self {
2428 Value::Array(v) => v.iter().any(|v| v.equal(other)),
2429 _ => self.equal(other),
2430 }
2431 }
2432
2433 pub fn fuzzy(&self, other: &Value) -> bool {
2435 match self {
2436 Value::Uuid(v) => match other {
2437 Value::Strand(w) => v.to_raw().as_str().fuzzy_match(w.as_str()),
2438 _ => false,
2439 },
2440 Value::Strand(v) => match other {
2441 Value::Strand(w) => v.as_str().fuzzy_match(w.as_str()),
2442 _ => false,
2443 },
2444 _ => self.equal(other),
2445 }
2446 }
2447
2448 pub fn all_fuzzy(&self, other: &Value) -> bool {
2450 match self {
2451 Value::Array(v) => v.iter().all(|v| v.fuzzy(other)),
2452 _ => self.fuzzy(other),
2453 }
2454 }
2455
2456 pub fn any_fuzzy(&self, other: &Value) -> bool {
2458 match self {
2459 Value::Array(v) => v.iter().any(|v| v.fuzzy(other)),
2460 _ => self.fuzzy(other),
2461 }
2462 }
2463
2464 pub fn contains(&self, other: &Value) -> bool {
2466 match self {
2467 Value::Array(v) => v.iter().any(|v| v.equal(other)),
2468 Value::Uuid(v) => match other {
2469 Value::Strand(w) => v.to_raw().contains(w.as_str()),
2470 _ => false,
2471 },
2472 Value::Strand(v) => match other {
2473 Value::Strand(w) => v.contains(w.as_str()),
2474 _ => false,
2475 },
2476 Value::Geometry(v) => match other {
2477 Value::Geometry(w) => v.contains(w),
2478 _ => false,
2479 },
2480 _ => false,
2481 }
2482 }
2483
2484 pub fn contains_all(&self, other: &Value) -> bool {
2486 match other {
2487 Value::Array(v) => v.iter().all(|v| match self {
2488 Value::Array(w) => w.iter().any(|w| v.equal(w)),
2489 Value::Geometry(_) => self.contains(v),
2490 _ => false,
2491 }),
2492 _ => false,
2493 }
2494 }
2495
2496 pub fn contains_any(&self, other: &Value) -> bool {
2498 match other {
2499 Value::Array(v) => v.iter().any(|v| match self {
2500 Value::Array(w) => w.iter().any(|w| v.equal(w)),
2501 Value::Geometry(_) => self.contains(v),
2502 _ => false,
2503 }),
2504 _ => false,
2505 }
2506 }
2507
2508 pub fn intersects(&self, other: &Value) -> bool {
2510 match self {
2511 Value::Geometry(v) => match other {
2512 Value::Geometry(w) => v.intersects(w),
2513 _ => false,
2514 },
2515 _ => false,
2516 }
2517 }
2518
2519 pub fn lexical_cmp(&self, other: &Value) -> Option<Ordering> {
2525 match (self, other) {
2526 (Value::Strand(a), Value::Strand(b)) => Some(lexicmp::lexical_cmp(a, b)),
2527 _ => self.partial_cmp(other),
2528 }
2529 }
2530
2531 pub fn natural_cmp(&self, other: &Value) -> Option<Ordering> {
2533 match (self, other) {
2534 (Value::Strand(a), Value::Strand(b)) => Some(lexicmp::natural_cmp(a, b)),
2535 _ => self.partial_cmp(other),
2536 }
2537 }
2538
2539 pub fn natural_lexical_cmp(&self, other: &Value) -> Option<Ordering> {
2541 match (self, other) {
2542 (Value::Strand(a), Value::Strand(b)) => Some(lexicmp::natural_lexical_cmp(a, b)),
2543 _ => self.partial_cmp(other),
2544 }
2545 }
2546}
2547
2548impl fmt::Display for Value {
2549 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2550 let mut f = Pretty::from(f);
2551 match self {
2552 Value::None => write!(f, "NONE"),
2553 Value::Null => write!(f, "NULL"),
2554 Value::Array(v) => write!(f, "{v}"),
2555 Value::Block(v) => write!(f, "{v}"),
2556 Value::Bool(v) => write!(f, "{v}"),
2557 Value::Bytes(v) => write!(f, "{v}"),
2558 Value::Cast(v) => write!(f, "{v}"),
2559 Value::Constant(v) => write!(f, "{v}"),
2560 Value::Datetime(v) => write!(f, "{v}"),
2561 Value::Duration(v) => write!(f, "{v}"),
2562 Value::Edges(v) => write!(f, "{v}"),
2563 Value::Expression(v) => write!(f, "{v}"),
2564 Value::Function(v) => write!(f, "{v}"),
2565 Value::Model(v) => write!(f, "{v}"),
2566 Value::Future(v) => write!(f, "{v}"),
2567 Value::Geometry(v) => write!(f, "{v}"),
2568 Value::Idiom(v) => write!(f, "{v}"),
2569 Value::Mock(v) => write!(f, "{v}"),
2570 Value::Number(v) => write!(f, "{v}"),
2571 Value::Object(v) => write!(f, "{v}"),
2572 Value::Param(v) => write!(f, "{v}"),
2573 Value::Range(v) => write!(f, "{v}"),
2574 Value::Regex(v) => write!(f, "{v}"),
2575 Value::Strand(v) => write!(f, "{v}"),
2576 Value::Query(v) => write!(f, "{v}"),
2577 Value::Subquery(v) => write!(f, "{v}"),
2578 Value::Table(v) => write!(f, "{v}"),
2579 Value::Thing(v) => write!(f, "{v}"),
2580 Value::Uuid(v) => write!(f, "{v}"),
2581 }
2582 }
2583}
2584
2585impl Value {
2586 pub(crate) fn writeable(&self) -> bool {
2588 match self {
2589 Value::Block(v) => v.writeable(),
2590 Value::Idiom(v) => v.writeable(),
2591 Value::Array(v) => v.iter().any(Value::writeable),
2592 Value::Object(v) => v.iter().any(|(_, v)| v.writeable()),
2593 Value::Function(v) => {
2594 v.is_custom() || v.is_script() || v.args().iter().any(Value::writeable)
2595 }
2596 Value::Model(m) => m.args.iter().any(Value::writeable),
2597 Value::Subquery(v) => v.writeable(),
2598 Value::Expression(v) => v.writeable(),
2599 _ => false,
2600 }
2601 }
2602 #[cfg_attr(not(target_arch = "wasm32"), async_recursion)]
2604 #[cfg_attr(target_arch = "wasm32", async_recursion(?Send))]
2605 pub(crate) async fn compute(
2606 &self,
2607 ctx: &Context<'_>,
2608 opt: &Options,
2609 txn: &Transaction,
2610 doc: Option<&'async_recursion CursorDoc<'_>>,
2611 ) -> Result<Value, Error> {
2612 let opt = &opt.dive(1)?;
2614
2615 match self {
2616 Value::Cast(v) => v.compute(ctx, opt, txn, doc).await,
2617 Value::Thing(v) => v.compute(ctx, opt, txn, doc).await,
2618 Value::Block(v) => v.compute(ctx, opt, txn, doc).await,
2619 Value::Range(v) => v.compute(ctx, opt, txn, doc).await,
2620 Value::Param(v) => v.compute(ctx, opt, txn, doc).await,
2621 Value::Idiom(v) => v.compute(ctx, opt, txn, doc).await,
2622 Value::Array(v) => v.compute(ctx, opt, txn, doc).await,
2623 Value::Object(v) => v.compute(ctx, opt, txn, doc).await,
2624 Value::Future(v) => v.compute(ctx, opt, txn, doc).await,
2625 Value::Constant(v) => v.compute(ctx, opt, txn, doc).await,
2626 Value::Function(v) => v.compute(ctx, opt, txn, doc).await,
2627 Value::Model(v) => v.compute(ctx, opt, txn, doc).await,
2628 Value::Subquery(v) => v.compute(ctx, opt, txn, doc).await,
2629 Value::Expression(v) => v.compute(ctx, opt, txn, doc).await,
2630 _ => Ok(self.to_owned()),
2631 }
2632 }
2633}
2634
2635pub(crate) trait TryAdd<Rhs = Self> {
2638 type Output;
2639 fn try_add(self, rhs: Rhs) -> Result<Self::Output, Error>;
2640}
2641
2642impl TryAdd for Value {
2643 type Output = Self;
2644 fn try_add(self, other: Self) -> Result<Self, Error> {
2645 Ok(match (self, other) {
2646 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_add(w)?),
2647 (Self::Strand(v), Self::Strand(w)) => Self::Strand(v + w),
2648 (Self::Datetime(v), Self::Duration(w)) => Self::Datetime(w + v),
2649 (Self::Duration(v), Self::Datetime(w)) => Self::Datetime(v + w),
2650 (Self::Duration(v), Self::Duration(w)) => Self::Duration(v + w),
2651 (v, w) => return Err(Error::TryAdd(v.to_raw_string(), w.to_raw_string())),
2652 })
2653 }
2654}
2655
2656pub(crate) trait TrySub<Rhs = Self> {
2659 type Output;
2660 fn try_sub(self, v: Self) -> Result<Self::Output, Error>;
2661}
2662
2663impl TrySub for Value {
2664 type Output = Self;
2665 fn try_sub(self, other: Self) -> Result<Self, Error> {
2666 Ok(match (self, other) {
2667 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_sub(w)?),
2668 (Self::Datetime(v), Self::Datetime(w)) => Self::Duration(v - w),
2669 (Self::Datetime(v), Self::Duration(w)) => Self::Datetime(w - v),
2670 (Self::Duration(v), Self::Datetime(w)) => Self::Datetime(v - w),
2671 (Self::Duration(v), Self::Duration(w)) => Self::Duration(v - w),
2672 (v, w) => return Err(Error::TrySub(v.to_raw_string(), w.to_raw_string())),
2673 })
2674 }
2675}
2676
2677pub(crate) trait TryMul<Rhs = Self> {
2680 type Output;
2681 fn try_mul(self, v: Self) -> Result<Self::Output, Error>;
2682}
2683
2684impl TryMul for Value {
2685 type Output = Self;
2686 fn try_mul(self, other: Self) -> Result<Self, Error> {
2687 Ok(match (self, other) {
2688 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_mul(w)?),
2689 (v, w) => return Err(Error::TryMul(v.to_raw_string(), w.to_raw_string())),
2690 })
2691 }
2692}
2693
2694pub(crate) trait TryDiv<Rhs = Self> {
2697 type Output;
2698 fn try_div(self, v: Self) -> Result<Self::Output, Error>;
2699}
2700
2701impl TryDiv for Value {
2702 type Output = Self;
2703 fn try_div(self, other: Self) -> Result<Self, Error> {
2704 Ok(match (self, other) {
2705 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_div(w)?),
2706 (v, w) => return Err(Error::TryDiv(v.to_raw_string(), w.to_raw_string())),
2707 })
2708 }
2709}
2710
2711pub(crate) trait TryPow<Rhs = Self> {
2714 type Output;
2715 fn try_pow(self, v: Self) -> Result<Self::Output, Error>;
2716}
2717
2718impl TryPow for Value {
2719 type Output = Self;
2720 fn try_pow(self, other: Self) -> Result<Self, Error> {
2721 Ok(match (self, other) {
2722 (Value::Number(v), Value::Number(w)) => Self::Number(v.try_pow(w)?),
2723 (v, w) => return Err(Error::TryPow(v.to_raw_string(), w.to_raw_string())),
2724 })
2725 }
2726}
2727
2728pub(crate) trait TryNeg<Rhs = Self> {
2731 type Output;
2732 fn try_neg(self) -> Result<Self::Output, Error>;
2733}
2734
2735impl TryNeg for Value {
2736 type Output = Self;
2737 fn try_neg(self) -> Result<Self, Error> {
2738 Ok(match self {
2739 Self::Number(n) => Self::Number(n.try_neg()?),
2740 v => return Err(Error::TryNeg(v.to_string())),
2741 })
2742 }
2743}
2744
2745#[cfg(test)]
2746mod tests {
2747
2748 use super::*;
2749 use crate::syn::test::Parse;
2750 use crate::uuid::Uuid;
2751
2752 #[test]
2753 fn check_none() {
2754 assert!(Value::None.is_none());
2755 assert!(!Value::Null.is_none());
2756 assert!(!Value::from(1).is_none());
2757 }
2758
2759 #[test]
2760 fn check_null() {
2761 assert!(Value::Null.is_null());
2762 assert!(!Value::None.is_null());
2763 assert!(!Value::from(1).is_null());
2764 }
2765
2766 #[test]
2767 fn check_true() {
2768 assert!(!Value::None.is_true());
2769 assert!(Value::Bool(true).is_true());
2770 assert!(!Value::Bool(false).is_true());
2771 assert!(!Value::from(1).is_true());
2772 assert!(!Value::from("something").is_true());
2773 }
2774
2775 #[test]
2776 fn check_false() {
2777 assert!(!Value::None.is_false());
2778 assert!(!Value::Bool(true).is_false());
2779 assert!(Value::Bool(false).is_false());
2780 assert!(!Value::from(1).is_false());
2781 assert!(!Value::from("something").is_false());
2782 }
2783
2784 #[test]
2785 fn convert_truthy() {
2786 assert!(!Value::None.is_truthy());
2787 assert!(!Value::Null.is_truthy());
2788 assert!(Value::Bool(true).is_truthy());
2789 assert!(!Value::Bool(false).is_truthy());
2790 assert!(!Value::from(0).is_truthy());
2791 assert!(Value::from(1).is_truthy());
2792 assert!(Value::from(-1).is_truthy());
2793 assert!(Value::from(1.1).is_truthy());
2794 assert!(Value::from(-1.1).is_truthy());
2795 assert!(Value::from("true").is_truthy());
2796 assert!(!Value::from("false").is_truthy());
2797 assert!(Value::from("falsey").is_truthy());
2798 assert!(Value::from("something").is_truthy());
2799 assert!(Value::from(Uuid::new()).is_truthy());
2800 }
2801
2802 #[test]
2803 fn convert_string() {
2804 assert_eq!(String::from("NONE"), Value::None.as_string());
2805 assert_eq!(String::from("NULL"), Value::Null.as_string());
2806 assert_eq!(String::from("true"), Value::Bool(true).as_string());
2807 assert_eq!(String::from("false"), Value::Bool(false).as_string());
2808 assert_eq!(String::from("0"), Value::from(0).as_string());
2809 assert_eq!(String::from("1"), Value::from(1).as_string());
2810 assert_eq!(String::from("-1"), Value::from(-1).as_string());
2811 assert_eq!(String::from("1.1f"), Value::from(1.1).as_string());
2812 assert_eq!(String::from("-1.1f"), Value::from(-1.1).as_string());
2813 assert_eq!(String::from("3"), Value::from("3").as_string());
2814 assert_eq!(String::from("true"), Value::from("true").as_string());
2815 assert_eq!(String::from("false"), Value::from("false").as_string());
2816 assert_eq!(String::from("something"), Value::from("something").as_string());
2817 }
2818
2819 #[test]
2820 fn check_size() {
2821 assert_eq!(64, std::mem::size_of::<Value>());
2822 assert_eq!(104, std::mem::size_of::<Error>());
2823 assert_eq!(104, std::mem::size_of::<Result<Value, Error>>());
2824 assert_eq!(24, std::mem::size_of::<crate::number::Number>());
2825 assert_eq!(24, std::mem::size_of::<crate::strand::Strand>());
2826 assert_eq!(16, std::mem::size_of::<crate::duration::Duration>());
2827 assert_eq!(12, std::mem::size_of::<crate::datetime::Datetime>());
2828 assert_eq!(24, std::mem::size_of::<crate::array::Array>());
2829 assert_eq!(24, std::mem::size_of::<crate::object::Object>());
2830 assert_eq!(56, std::mem::size_of::<crate::geometry::Geometry>());
2831 assert_eq!(24, std::mem::size_of::<crate::param::Param>());
2832 assert_eq!(24, std::mem::size_of::<crate::idiom::Idiom>());
2833 assert_eq!(24, std::mem::size_of::<crate::table::Table>());
2834 assert_eq!(56, std::mem::size_of::<crate::thing::Thing>());
2835 assert_eq!(40, std::mem::size_of::<crate::mock::Mock>());
2836 assert_eq!(32, std::mem::size_of::<crate::regex::Regex>());
2837 assert_eq!(8, std::mem::size_of::<Box<crate::range::Range>>());
2838 assert_eq!(8, std::mem::size_of::<Box<crate::edges::Edges>>());
2839 assert_eq!(8, std::mem::size_of::<Box<crate::function::Function>>());
2840 assert_eq!(8, std::mem::size_of::<Box<crate::subquery::Subquery>>());
2841 assert_eq!(8, std::mem::size_of::<Box<crate::expression::Expression>>());
2842 }
2843
2844 #[test]
2845 fn check_serialize() {
2846 let enc: Vec<u8> = Value::None.try_into().unwrap();
2847 assert_eq!(2, enc.len());
2848 let enc: Vec<u8> = Value::Null.try_into().unwrap();
2849 assert_eq!(2, enc.len());
2850 let enc: Vec<u8> = Value::Bool(true).try_into().unwrap();
2851 assert_eq!(3, enc.len());
2852 let enc: Vec<u8> = Value::Bool(false).try_into().unwrap();
2853 assert_eq!(3, enc.len());
2854 let enc: Vec<u8> = Value::from("test").try_into().unwrap();
2855 assert_eq!(8, enc.len());
2856 let enc: Vec<u8> = Value::parse("{ hello: 'world' }").try_into().unwrap();
2857 assert_eq!(19, enc.len());
2858 let enc: Vec<u8> = Value::parse("{ compact: true, schema: 0 }").try_into().unwrap();
2859 assert_eq!(27, enc.len());
2860 }
2861
2862 #[test]
2863 fn serialize_deserialize() {
2864 let val = Value::parse(
2865 "{ test: { something: [1, 'two', null, test:tobie, { trueee: false, noneee: nulll }] } }",
2866 );
2867 let res = Value::parse(
2868 "{ test: { something: [1, 'two', null, test:tobie, { trueee: false, noneee: nulll }] } }",
2869 );
2870 let enc: Vec<u8> = val.try_into().unwrap();
2871 let dec: Value = enc.try_into().unwrap();
2872 assert_eq!(res, dec);
2873 }
2874}