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::Regex => self.coerce_to_regex().map(Value::from),
1359 Kind::Range => self.coerce_to_range().map(Value::from),
1360 Kind::Function(_, _) => self.coerce_to_function().map(Value::from),
1361 Kind::Set(t, l) => match l {
1362 Some(l) => self.coerce_to_set_type_len(t, l).map(Value::from),
1363 None => self.coerce_to_set_type(t).map(Value::from),
1364 },
1365 Kind::Array(t, l) => match l {
1366 Some(l) => self.coerce_to_array_type_len(t, l).map(Value::from),
1367 None => self.coerce_to_array_type(t).map(Value::from),
1368 },
1369 Kind::Record(t) => match t.is_empty() {
1370 true => self.coerce_to_record().map(Value::from),
1371 false => self.coerce_to_record_type(t).map(Value::from),
1372 },
1373 Kind::Geometry(t) => match t.is_empty() {
1374 true => self.coerce_to_geometry().map(Value::from),
1375 false => self.coerce_to_geometry_type(t).map(Value::from),
1376 },
1377 Kind::Option(k) => match self {
1378 Self::None => Ok(Self::None),
1379 v => v.coerce_to(k),
1380 },
1381 Kind::Either(k) => {
1382 let mut val = self;
1383 for k in k {
1384 match val.coerce_to(k) {
1385 Err(Error::CoerceTo {
1386 from,
1387 ..
1388 }) => val = from,
1389 Err(e) => return Err(e),
1390 Ok(v) => return Ok(v),
1391 }
1392 }
1393 Err(Error::CoerceTo {
1394 from: val,
1395 into: kind.to_string(),
1396 })
1397 }
1398 Kind::Literal(lit) => self.coerce_to_literal(lit),
1399 Kind::References(_, _) => Err(Error::CoerceTo {
1400 from: self,
1401 into: kind.to_string(),
1402 }),
1403 };
1404 match res {
1406 Err(Error::CoerceTo {
1408 from,
1409 ..
1410 }) => Err(Error::CoerceTo {
1411 from,
1412 into: kind.to_string(),
1413 }),
1414 Err(e) => Err(e),
1416 Ok(v) => Ok(v),
1418 }
1419 }
1420
1421 pub fn coerce_to_i64(self) -> Result<i64, Error> {
1423 match self {
1424 Value::Number(Number::Int(v)) => Ok(v),
1426 Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(v as i64),
1428 Value::Number(Number::Decimal(v)) if v.is_integer() => match v.try_into() {
1430 Ok(v) => Ok(v),
1432 _ => Err(Error::CoerceTo {
1434 from: self,
1435 into: "i64".into(),
1436 }),
1437 },
1438 _ => Err(Error::CoerceTo {
1440 from: self,
1441 into: "i64".into(),
1442 }),
1443 }
1444 }
1445
1446 pub(crate) fn coerce_to_u64(self) -> Result<u64, Error> {
1448 match self {
1449 Value::Number(Number::Int(v)) => Ok(v as u64),
1451 Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(v as u64),
1453 Value::Number(Number::Decimal(v)) if v.is_integer() => match v.try_into() {
1455 Ok(v) => Ok(v),
1457 _ => Err(Error::CoerceTo {
1459 from: self,
1460 into: "u64".into(),
1461 }),
1462 },
1463 _ => Err(Error::CoerceTo {
1465 from: self,
1466 into: "u64".into(),
1467 }),
1468 }
1469 }
1470
1471 pub(crate) fn coerce_to_f64(self) -> Result<f64, Error> {
1473 match self {
1474 Value::Number(Number::Float(v)) => Ok(v),
1476 Value::Number(Number::Int(v)) => Ok(v as f64),
1478 Value::Number(Number::Decimal(v)) => match v.try_into() {
1480 Ok(v) => Ok(v),
1482 _ => Err(Error::CoerceTo {
1484 from: self,
1485 into: "f64".into(),
1486 }),
1487 },
1488 _ => Err(Error::CoerceTo {
1490 from: self,
1491 into: "f64".into(),
1492 }),
1493 }
1494 }
1495
1496 pub(crate) fn coerce_to_literal(self, literal: &Literal) -> Result<Value, Error> {
1498 if literal.validate_value(&self) {
1499 Ok(self)
1500 } else {
1501 Err(Error::CoerceTo {
1502 from: self,
1503 into: literal.to_string(),
1504 })
1505 }
1506 }
1507
1508 pub(crate) fn coerce_to_null(self) -> Result<Value, Error> {
1510 match self {
1511 Value::Null => Ok(Value::Null),
1513 _ => Err(Error::CoerceTo {
1515 from: self,
1516 into: "null".into(),
1517 }),
1518 }
1519 }
1520
1521 pub(crate) fn coerce_to_bool(self) -> Result<bool, Error> {
1523 match self {
1524 Value::Bool(v) => Ok(v),
1526 _ => Err(Error::CoerceTo {
1528 from: self,
1529 into: "bool".into(),
1530 }),
1531 }
1532 }
1533
1534 pub(crate) fn coerce_to_int(self) -> Result<Number, Error> {
1536 match self {
1537 Value::Number(v) if v.is_int() => Ok(v),
1539 Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(Number::Int(v as i64)),
1541 Value::Number(Number::Decimal(v)) if v.is_integer() => match v.to_i64() {
1543 Some(v) => Ok(Number::Int(v)),
1545 _ => Err(Error::CoerceTo {
1547 from: self,
1548 into: "int".into(),
1549 }),
1550 },
1551 _ => Err(Error::CoerceTo {
1553 from: self,
1554 into: "int".into(),
1555 }),
1556 }
1557 }
1558
1559 pub(crate) fn coerce_to_float(self) -> Result<Number, Error> {
1561 match self {
1562 Value::Number(v) if v.is_float() => Ok(v),
1564 Value::Number(Number::Int(v)) => Ok(Number::Float(v as f64)),
1566 Value::Number(Number::Decimal(ref v)) => match v.to_f64() {
1568 Some(v) => Ok(Number::Float(v)),
1570 None => Err(Error::CoerceTo {
1572 from: self,
1573 into: "float".into(),
1574 }),
1575 },
1576 _ => Err(Error::CoerceTo {
1578 from: self,
1579 into: "float".into(),
1580 }),
1581 }
1582 }
1583
1584 pub(crate) fn coerce_to_decimal(self) -> Result<Number, Error> {
1586 match self {
1587 Value::Number(v) if v.is_decimal() => Ok(v),
1589 Value::Number(Number::Int(v)) => match Decimal::from_i64(v) {
1591 Some(v) => Ok(Number::Decimal(v)),
1593 None => Err(Error::CoerceTo {
1595 from: self,
1596 into: "decimal".into(),
1597 }),
1598 },
1599 Value::Number(Number::Float(v)) => match Decimal::from_f64(v) {
1601 Some(v) => Ok(Number::Decimal(v)),
1603 None => Err(Error::CoerceTo {
1605 from: self,
1606 into: "decimal".into(),
1607 }),
1608 },
1609 _ => Err(Error::CoerceTo {
1611 from: self,
1612 into: "decimal".into(),
1613 }),
1614 }
1615 }
1616
1617 pub(crate) fn coerce_to_number(self) -> Result<Number, Error> {
1619 match self {
1620 Value::Number(v) => Ok(v),
1622 _ => Err(Error::CoerceTo {
1624 from: self,
1625 into: "number".into(),
1626 }),
1627 }
1628 }
1629
1630 pub(crate) fn coerce_to_regex(self) -> Result<Regex, Error> {
1632 match self {
1633 Value::Regex(v) => Ok(v),
1635 Value::Strand(v) => Ok(v.as_str().parse()?),
1637 _ => Err(Error::CoerceTo {
1639 from: self,
1640 into: "regex".into(),
1641 }),
1642 }
1643 }
1644
1645 pub(crate) fn coerce_to_string(self) -> Result<String, Error> {
1647 match self {
1648 Value::Uuid(v) => Ok(v.to_raw()),
1650 Value::Datetime(v) => Ok(v.to_raw()),
1652 Value::Strand(v) => Ok(v.as_string()),
1654 _ => Err(Error::CoerceTo {
1656 from: self,
1657 into: "string".into(),
1658 }),
1659 }
1660 }
1661
1662 pub(crate) fn coerce_to_strand(self) -> Result<Strand, Error> {
1664 match self {
1665 Value::Uuid(v) => Ok(v.to_raw().into()),
1667 Value::Datetime(v) => Ok(v.to_raw().into()),
1669 Value::Strand(v) => Ok(v),
1671 _ => Err(Error::CoerceTo {
1673 from: self,
1674 into: "string".into(),
1675 }),
1676 }
1677 }
1678
1679 pub(crate) fn coerce_to_uuid(self) -> Result<Uuid, Error> {
1681 match self {
1682 Value::Uuid(v) => Ok(v),
1684 _ => Err(Error::CoerceTo {
1686 from: self,
1687 into: "uuid".into(),
1688 }),
1689 }
1690 }
1691
1692 pub(crate) fn coerce_to_function(self) -> Result<Closure, Error> {
1694 match self {
1695 Value::Closure(v) => Ok(*v),
1697 _ => Err(Error::CoerceTo {
1699 from: self,
1700 into: "function".into(),
1701 }),
1702 }
1703 }
1704
1705 pub(crate) fn coerce_to_datetime(self) -> Result<Datetime, Error> {
1707 match self {
1708 Value::Datetime(v) => Ok(v),
1710 _ => Err(Error::CoerceTo {
1712 from: self,
1713 into: "datetime".into(),
1714 }),
1715 }
1716 }
1717
1718 pub(crate) fn coerce_to_duration(self) -> Result<Duration, Error> {
1720 match self {
1721 Value::Duration(v) => Ok(v),
1723 _ => Err(Error::CoerceTo {
1725 from: self,
1726 into: "duration".into(),
1727 }),
1728 }
1729 }
1730
1731 pub(crate) fn coerce_to_bytes(self) -> Result<Bytes, Error> {
1733 match self {
1734 Value::Bytes(v) => Ok(v),
1736 _ => Err(Error::CoerceTo {
1738 from: self,
1739 into: "bytes".into(),
1740 }),
1741 }
1742 }
1743
1744 pub(crate) fn coerce_to_object(self) -> Result<Object, Error> {
1746 match self {
1747 Value::Object(v) => Ok(v),
1749 _ => Err(Error::CoerceTo {
1751 from: self,
1752 into: "object".into(),
1753 }),
1754 }
1755 }
1756
1757 pub(crate) fn coerce_to_array(self) -> Result<Array, Error> {
1759 match self {
1760 Value::Array(v) => Ok(v),
1762 _ => Err(Error::CoerceTo {
1764 from: self,
1765 into: "array".into(),
1766 }),
1767 }
1768 }
1769
1770 pub(crate) fn coerce_to_range(self) -> Result<Range, Error> {
1772 match self {
1773 Value::Range(v) => Ok(*v),
1775 _ => Err(Error::CoerceTo {
1777 from: self,
1778 into: "range".into(),
1779 }),
1780 }
1781 }
1782
1783 pub(crate) fn coerce_to_point(self) -> Result<Geometry, Error> {
1785 match self {
1786 Value::Geometry(Geometry::Point(v)) => Ok(v.into()),
1788 _ => Err(Error::CoerceTo {
1790 from: self,
1791 into: "point".into(),
1792 }),
1793 }
1794 }
1795
1796 pub(crate) fn coerce_to_record(self) -> Result<Thing, Error> {
1798 match self {
1799 Value::Thing(v) => Ok(v),
1801 _ => Err(Error::CoerceTo {
1803 from: self,
1804 into: "record".into(),
1805 }),
1806 }
1807 }
1808
1809 pub(crate) fn coerce_to_geometry(self) -> Result<Geometry, Error> {
1811 match self {
1812 Value::Geometry(v) => Ok(v),
1814 _ => Err(Error::CoerceTo {
1816 from: self,
1817 into: "geometry".into(),
1818 }),
1819 }
1820 }
1821
1822 pub(crate) fn coerce_to_record_type(self, val: &[Table]) -> Result<Thing, Error> {
1824 match self {
1825 Value::Thing(v) if self.is_record_type(val) => Ok(v),
1827 _ => Err(Error::CoerceTo {
1829 from: self,
1830 into: "record".into(),
1831 }),
1832 }
1833 }
1834
1835 pub(crate) fn coerce_to_geometry_type(self, val: &[String]) -> Result<Geometry, Error> {
1837 match self {
1838 Value::Geometry(v) if self.is_geometry_type(val) => Ok(v),
1840 _ => Err(Error::CoerceTo {
1842 from: self,
1843 into: "geometry".into(),
1844 }),
1845 }
1846 }
1847
1848 pub(crate) fn coerce_to_array_type(self, kind: &Kind) -> Result<Array, Error> {
1850 self.coerce_to_array()?
1851 .into_iter()
1852 .map(|value| value.coerce_to(kind))
1853 .collect::<Result<Array, Error>>()
1854 .map_err(|e| match e {
1855 Error::CoerceTo {
1856 from,
1857 ..
1858 } => Error::CoerceTo {
1859 from,
1860 into: format!("array<{kind}>"),
1861 },
1862 e => e,
1863 })
1864 }
1865
1866 pub(crate) fn coerce_to_array_type_len(self, kind: &Kind, len: &u64) -> Result<Array, Error> {
1868 self.coerce_to_array()?
1869 .into_iter()
1870 .map(|value| value.coerce_to(kind))
1871 .collect::<Result<Array, Error>>()
1872 .map_err(|e| match e {
1873 Error::CoerceTo {
1874 from,
1875 ..
1876 } => Error::CoerceTo {
1877 from,
1878 into: format!("array<{kind}, {len}>"),
1879 },
1880 e => e,
1881 })
1882 .and_then(|v| match v.len() {
1883 v if v > *len as usize => Err(Error::LengthInvalid {
1884 kind: format!("array<{kind}, {len}>"),
1885 size: v,
1886 }),
1887 _ => Ok(v),
1888 })
1889 }
1890
1891 pub(crate) fn coerce_to_set_type(self, kind: &Kind) -> Result<Array, Error> {
1893 self.coerce_to_array()?
1894 .uniq()
1895 .into_iter()
1896 .map(|value| value.coerce_to(kind))
1897 .collect::<Result<Array, Error>>()
1898 .map_err(|e| match e {
1899 Error::CoerceTo {
1900 from,
1901 ..
1902 } => Error::CoerceTo {
1903 from,
1904 into: format!("set<{kind}>"),
1905 },
1906 e => e,
1907 })
1908 }
1909
1910 pub(crate) fn coerce_to_set_type_len(self, kind: &Kind, len: &u64) -> Result<Array, Error> {
1912 self.coerce_to_array()?
1913 .uniq()
1914 .into_iter()
1915 .map(|value| value.coerce_to(kind))
1916 .collect::<Result<Array, Error>>()
1917 .map_err(|e| match e {
1918 Error::CoerceTo {
1919 from,
1920 ..
1921 } => Error::CoerceTo {
1922 from,
1923 into: format!("set<{kind}, {len}>"),
1924 },
1925 e => e,
1926 })
1927 .and_then(|v| match v.len() {
1928 v if v > *len as usize => Err(Error::LengthInvalid {
1929 kind: format!("set<{kind}, {len}>"),
1930 size: v,
1931 }),
1932 _ => Ok(v),
1933 })
1934 }
1935
1936 pub(crate) fn convert_to(self, kind: &Kind) -> Result<Value, Error> {
1942 let res = match kind {
1944 Kind::Any => Ok(self),
1945 Kind::Null => self.convert_to_null(),
1946 Kind::Bool => self.convert_to_bool().map(Value::from),
1947 Kind::Int => self.convert_to_int().map(Value::from),
1948 Kind::Float => self.convert_to_float().map(Value::from),
1949 Kind::Decimal => self.convert_to_decimal().map(Value::from),
1950 Kind::Number => self.convert_to_number().map(Value::from),
1951 Kind::String => self.convert_to_strand().map(Value::from),
1952 Kind::Datetime => self.convert_to_datetime().map(Value::from),
1953 Kind::Duration => self.convert_to_duration().map(Value::from),
1954 Kind::Object => self.convert_to_object().map(Value::from),
1955 Kind::Point => self.convert_to_point().map(Value::from),
1956 Kind::Bytes => self.convert_to_bytes().map(Value::from),
1957 Kind::Uuid => self.convert_to_uuid().map(Value::from),
1958 Kind::Regex => self.convert_to_regex().map(Value::from),
1959 Kind::Range => self.convert_to_range().map(Value::from),
1960 Kind::Function(_, _) => self.convert_to_function().map(Value::from),
1961 Kind::Set(t, l) => match l {
1962 Some(l) => self.convert_to_set_type_len(t, l).map(Value::from),
1963 None => self.convert_to_set_type(t).map(Value::from),
1964 },
1965 Kind::Array(t, l) => match l {
1966 Some(l) => self.convert_to_array_type_len(t, l).map(Value::from),
1967 None => self.convert_to_array_type(t).map(Value::from),
1968 },
1969 Kind::Record(t) => match t.is_empty() {
1970 true => self.convert_to_record().map(Value::from),
1971 false => self.convert_to_record_type(t).map(Value::from),
1972 },
1973 Kind::Geometry(t) => match t.is_empty() {
1974 true => self.convert_to_geometry().map(Value::from),
1975 false => self.convert_to_geometry_type(t).map(Value::from),
1976 },
1977 Kind::Option(k) => match self {
1978 Self::None => Ok(Self::None),
1979 v => v.convert_to(k),
1980 },
1981 Kind::Either(k) => {
1982 let mut val = self;
1983 for k in k {
1984 match val.convert_to(k) {
1985 Err(Error::ConvertTo {
1986 from,
1987 ..
1988 }) => val = from,
1989 Err(e) => return Err(e),
1990 Ok(v) => return Ok(v),
1991 }
1992 }
1993 Err(Error::ConvertTo {
1994 from: val,
1995 into: kind.to_string(),
1996 })
1997 }
1998 Kind::Literal(lit) => self.convert_to_literal(lit),
1999 Kind::References(_, _) => Err(Error::CoerceTo {
2000 from: self,
2001 into: kind.to_string(),
2002 }),
2003 };
2004 match res {
2006 Err(Error::ConvertTo {
2008 from,
2009 ..
2010 }) => Err(Error::ConvertTo {
2011 from,
2012 into: kind.to_string(),
2013 }),
2014 Err(e) => Err(e),
2016 Ok(v) => Ok(v),
2018 }
2019 }
2020
2021 pub(crate) fn convert_to_literal(self, literal: &Literal) -> Result<Value, Error> {
2023 if literal.validate_value(&self) {
2024 Ok(self)
2025 } else {
2026 Err(Error::ConvertTo {
2027 from: self,
2028 into: literal.to_string(),
2029 })
2030 }
2031 }
2032
2033 pub(crate) fn convert_to_null(self) -> Result<Value, Error> {
2035 match self {
2036 Value::Null => Ok(Value::Null),
2038 _ => Err(Error::ConvertTo {
2040 from: self,
2041 into: "null".into(),
2042 }),
2043 }
2044 }
2045
2046 pub(crate) fn convert_to_bool(self) -> Result<bool, Error> {
2048 match self {
2049 Value::Bool(v) => Ok(v),
2051 Value::Strand(ref v) => match v.parse::<bool>() {
2053 Ok(v) => Ok(v),
2055 _ => Err(Error::ConvertTo {
2057 from: self,
2058 into: "bool".into(),
2059 }),
2060 },
2061 _ => Err(Error::ConvertTo {
2063 from: self,
2064 into: "bool".into(),
2065 }),
2066 }
2067 }
2068
2069 pub(crate) fn convert_to_int(self) -> Result<Number, Error> {
2071 match self {
2072 Value::Number(v) if v.is_int() => Ok(v),
2074 Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(Number::Int(v as i64)),
2076 Value::Number(Number::Decimal(v)) if v.is_integer() => match v.try_into() {
2078 Ok(v) => Ok(Number::Int(v)),
2080 _ => Err(Error::ConvertTo {
2082 from: self,
2083 into: "int".into(),
2084 }),
2085 },
2086 Value::Strand(ref v) => match v.parse::<i64>() {
2088 Ok(v) => Ok(Number::Int(v)),
2090 _ => Err(Error::ConvertTo {
2092 from: self,
2093 into: "int".into(),
2094 }),
2095 },
2096 _ => Err(Error::ConvertTo {
2098 from: self,
2099 into: "int".into(),
2100 }),
2101 }
2102 }
2103
2104 pub(crate) fn convert_to_float(self) -> Result<Number, Error> {
2106 match self {
2107 Value::Number(v) if v.is_float() => Ok(v),
2109 Value::Number(Number::Int(v)) => Ok(Number::Float(v as f64)),
2111 Value::Number(Number::Decimal(v)) => match v.try_into() {
2113 Ok(v) => Ok(Number::Float(v)),
2115 _ => Err(Error::ConvertTo {
2117 from: self,
2118 into: "float".into(),
2119 }),
2120 },
2121 Value::Strand(ref v) => match v.parse::<f64>() {
2123 Ok(v) => Ok(Number::Float(v)),
2125 _ => Err(Error::ConvertTo {
2127 from: self,
2128 into: "float".into(),
2129 }),
2130 },
2131 _ => Err(Error::ConvertTo {
2133 from: self,
2134 into: "float".into(),
2135 }),
2136 }
2137 }
2138
2139 pub(crate) fn convert_to_decimal(self) -> Result<Number, Error> {
2141 match self {
2142 Value::Number(v) if v.is_decimal() => Ok(v),
2144 Value::Number(Number::Int(ref v)) => Ok(Number::Decimal(Decimal::from(*v))),
2146 Value::Number(Number::Float(ref v)) => match Decimal::try_from(*v) {
2148 Ok(v) => Ok(Number::Decimal(v)),
2150 _ => Err(Error::ConvertTo {
2152 from: self,
2153 into: "decimal".into(),
2154 }),
2155 },
2156 Value::Strand(ref v) => match Decimal::from_str(v) {
2158 Ok(v) => Ok(Number::Decimal(v)),
2160 _ => Err(Error::ConvertTo {
2162 from: self,
2163 into: "decimal".into(),
2164 }),
2165 },
2166 _ => Err(Error::ConvertTo {
2168 from: self,
2169 into: "decimal".into(),
2170 }),
2171 }
2172 }
2173
2174 pub(crate) fn convert_to_number(self) -> Result<Number, Error> {
2176 match self {
2177 Value::Number(v) => Ok(v),
2179 Value::Strand(ref v) => match Number::from_str(v) {
2181 Ok(v) => Ok(v),
2183 _ => Err(Error::ConvertTo {
2185 from: self,
2186 into: "number".into(),
2187 }),
2188 },
2189 _ => Err(Error::ConvertTo {
2191 from: self,
2192 into: "number".into(),
2193 }),
2194 }
2195 }
2196
2197 pub fn convert_to_string(self) -> Result<String, Error> {
2199 match self {
2200 Value::Bytes(_) => Err(Error::ConvertTo {
2202 from: self,
2203 into: "string".into(),
2204 }),
2205 Value::None => Err(Error::ConvertTo {
2207 from: self,
2208 into: "string".into(),
2209 }),
2210 Value::Null => Err(Error::ConvertTo {
2212 from: self,
2213 into: "string".into(),
2214 }),
2215 _ => Ok(self.as_string()),
2217 }
2218 }
2219
2220 pub(crate) fn convert_to_strand(self) -> Result<Strand, Error> {
2222 match self {
2223 Value::Bytes(_) => Err(Error::ConvertTo {
2225 from: self,
2226 into: "string".into(),
2227 }),
2228 Value::None => Err(Error::ConvertTo {
2230 from: self,
2231 into: "string".into(),
2232 }),
2233 Value::Null => Err(Error::ConvertTo {
2235 from: self,
2236 into: "string".into(),
2237 }),
2238 Value::Strand(v) => Ok(v),
2240 Value::Uuid(v) => Ok(v.to_raw().into()),
2242 Value::Datetime(v) => Ok(v.to_raw().into()),
2244 _ => Ok(self.to_string().into()),
2246 }
2247 }
2248
2249 pub(crate) fn convert_to_uuid(self) -> Result<Uuid, Error> {
2251 match self {
2252 Value::Uuid(v) => Ok(v),
2254 Value::Strand(ref v) => match Uuid::from_str(v) {
2256 Ok(v) => Ok(v),
2258 _ => Err(Error::ConvertTo {
2260 from: self,
2261 into: "uuid".into(),
2262 }),
2263 },
2264 _ => Err(Error::ConvertTo {
2266 from: self,
2267 into: "uuid".into(),
2268 }),
2269 }
2270 }
2271
2272 pub(crate) fn convert_to_regex(self) -> Result<Regex, Error> {
2274 match self {
2275 Value::Regex(v) => Ok(v),
2277 Value::Strand(ref v) => match Regex::from_str(v) {
2279 Ok(v) => Ok(v),
2281 _ => Err(Error::ConvertTo {
2283 from: self,
2284 into: "regex".into(),
2285 }),
2286 },
2287 _ => Err(Error::ConvertTo {
2289 from: self,
2290 into: "regex".into(),
2291 }),
2292 }
2293 }
2294
2295 pub(crate) fn convert_to_function(self) -> Result<Closure, Error> {
2297 match self {
2298 Value::Closure(v) => Ok(*v),
2300 _ => Err(Error::ConvertTo {
2302 from: self,
2303 into: "function".into(),
2304 }),
2305 }
2306 }
2307
2308 pub(crate) fn convert_to_datetime(self) -> Result<Datetime, Error> {
2310 match self {
2311 Value::Datetime(v) => Ok(v),
2313 Value::Strand(ref v) => match Datetime::from_str(v) {
2315 Ok(v) => Ok(v),
2317 _ => Err(Error::ConvertTo {
2319 from: self,
2320 into: "datetime".into(),
2321 }),
2322 },
2323 _ => Err(Error::ConvertTo {
2325 from: self,
2326 into: "datetime".into(),
2327 }),
2328 }
2329 }
2330
2331 pub(crate) fn convert_to_duration(self) -> Result<Duration, Error> {
2333 match self {
2334 Value::Duration(v) => Ok(v),
2336 Value::Strand(ref v) => match Duration::from_str(v) {
2338 Ok(v) => Ok(v),
2340 _ => Err(Error::ConvertTo {
2342 from: self,
2343 into: "duration".into(),
2344 }),
2345 },
2346 _ => Err(Error::ConvertTo {
2348 from: self,
2349 into: "duration".into(),
2350 }),
2351 }
2352 }
2353
2354 pub(crate) fn convert_to_bytes(self) -> Result<Bytes, Error> {
2356 match self {
2357 Value::Bytes(v) => Ok(v),
2359 Value::Strand(s) => Ok(Bytes(s.0.into_bytes())),
2361 _ => Err(Error::ConvertTo {
2363 from: self,
2364 into: "bytes".into(),
2365 }),
2366 }
2367 }
2368
2369 pub(crate) fn convert_to_object(self) -> Result<Object, Error> {
2371 match self {
2372 Value::Object(v) => Ok(v),
2374 _ => Err(Error::ConvertTo {
2376 from: self,
2377 into: "object".into(),
2378 }),
2379 }
2380 }
2381
2382 pub(crate) fn convert_to_array(self) -> Result<Array, Error> {
2384 match self {
2385 Value::Array(v) => Ok(v),
2387 Value::Range(r) => {
2389 let range: std::ops::Range<i64> = r.deref().to_owned().try_into()?;
2390 Ok(range.into_iter().map(Value::from).collect::<Vec<Value>>().into())
2391 }
2392 _ => Err(Error::ConvertTo {
2394 from: self,
2395 into: "array".into(),
2396 }),
2397 }
2398 }
2399
2400 pub(crate) fn convert_to_range(self) -> Result<Range, Error> {
2402 match self {
2403 Value::Range(r) => Ok(*r),
2405 Value::Array(v) if v.len() == 2 => {
2407 let mut v = v;
2408 Ok(Range {
2409 beg: Bound::Included(v.remove(0)),
2410 end: Bound::Excluded(v.remove(0)),
2411 })
2412 }
2413 _ => Err(Error::ConvertTo {
2415 from: self,
2416 into: "range".into(),
2417 }),
2418 }
2419 }
2420
2421 pub(crate) fn convert_to_point(self) -> Result<Geometry, Error> {
2423 match self {
2424 Value::Geometry(Geometry::Point(v)) => Ok(v.into()),
2426 Value::Array(ref v) if v.len() == 2 => match v.as_slice() {
2428 [Value::Number(v), Value::Number(w)] => Ok((v.to_float(), w.to_float()).into()),
2430 _ => Err(Error::ConvertTo {
2432 from: self,
2433 into: "point".into(),
2434 }),
2435 },
2436 _ => Err(Error::ConvertTo {
2438 from: self,
2439 into: "point".into(),
2440 }),
2441 }
2442 }
2443
2444 pub(crate) fn convert_to_record(self) -> Result<Thing, Error> {
2446 match self {
2447 Value::Thing(v) => Ok(v),
2449 Value::Strand(ref v) => match Thing::from_str(v) {
2451 Ok(v) => Ok(v),
2453 _ => Err(Error::ConvertTo {
2455 from: self,
2456 into: "record".into(),
2457 }),
2458 },
2459 _ => Err(Error::ConvertTo {
2461 from: self,
2462 into: "record".into(),
2463 }),
2464 }
2465 }
2466
2467 pub(crate) fn convert_to_geometry(self) -> Result<Geometry, Error> {
2469 match self {
2470 Value::Geometry(v) => Ok(v),
2472 _ => Err(Error::ConvertTo {
2474 from: self,
2475 into: "geometry".into(),
2476 }),
2477 }
2478 }
2479
2480 pub(crate) fn convert_to_record_type(self, val: &[Table]) -> Result<Thing, Error> {
2482 match self {
2483 Value::Thing(v) if self.is_record_type(val) => Ok(v),
2485 Value::Strand(ref v) => match Thing::from_str(v) {
2487 Ok(v) if v.is_record_type(val) => Ok(v),
2489 _ => Err(Error::ConvertTo {
2491 from: self,
2492 into: "record".into(),
2493 }),
2494 },
2495 _ => Err(Error::ConvertTo {
2497 from: self,
2498 into: "record".into(),
2499 }),
2500 }
2501 }
2502
2503 pub(crate) fn convert_to_geometry_type(self, val: &[String]) -> Result<Geometry, Error> {
2505 match self {
2506 Value::Geometry(v) if self.is_geometry_type(val) => Ok(v),
2508 _ => Err(Error::ConvertTo {
2510 from: self,
2511 into: "geometry".into(),
2512 }),
2513 }
2514 }
2515
2516 pub(crate) fn convert_to_array_type(self, kind: &Kind) -> Result<Array, Error> {
2518 self.convert_to_array()?
2519 .into_iter()
2520 .map(|value| value.convert_to(kind))
2521 .collect::<Result<Array, Error>>()
2522 .map_err(|e| match e {
2523 Error::ConvertTo {
2524 from,
2525 ..
2526 } => Error::ConvertTo {
2527 from,
2528 into: format!("array<{kind}>"),
2529 },
2530 e => e,
2531 })
2532 }
2533
2534 pub(crate) fn convert_to_array_type_len(self, kind: &Kind, len: &u64) -> Result<Array, Error> {
2536 self.convert_to_array()?
2537 .into_iter()
2538 .map(|value| value.convert_to(kind))
2539 .collect::<Result<Array, Error>>()
2540 .map_err(|e| match e {
2541 Error::ConvertTo {
2542 from,
2543 ..
2544 } => Error::ConvertTo {
2545 from,
2546 into: format!("array<{kind}, {len}>"),
2547 },
2548 e => e,
2549 })
2550 .and_then(|v| match v.len() {
2551 v if v > *len as usize => Err(Error::LengthInvalid {
2552 kind: format!("array<{kind}, {len}>"),
2553 size: v,
2554 }),
2555 _ => Ok(v),
2556 })
2557 }
2558
2559 pub(crate) fn convert_to_set_type(self, kind: &Kind) -> Result<Array, Error> {
2561 self.convert_to_array()?
2562 .uniq()
2563 .into_iter()
2564 .map(|value| value.convert_to(kind))
2565 .collect::<Result<Array, Error>>()
2566 .map_err(|e| match e {
2567 Error::ConvertTo {
2568 from,
2569 ..
2570 } => Error::ConvertTo {
2571 from,
2572 into: format!("set<{kind}>"),
2573 },
2574 e => e,
2575 })
2576 }
2577
2578 pub(crate) fn convert_to_set_type_len(self, kind: &Kind, len: &u64) -> Result<Array, Error> {
2580 self.convert_to_array()?
2581 .uniq()
2582 .into_iter()
2583 .map(|value| value.convert_to(kind))
2584 .collect::<Result<Array, Error>>()
2585 .map_err(|e| match e {
2586 Error::ConvertTo {
2587 from,
2588 ..
2589 } => Error::ConvertTo {
2590 from,
2591 into: format!("set<{kind}, {len}>"),
2592 },
2593 e => e,
2594 })
2595 .and_then(|v| match v.len() {
2596 v if v > *len as usize => Err(Error::LengthInvalid {
2597 kind: format!("set<{kind}, {len}>"),
2598 size: v,
2599 }),
2600 _ => Ok(v),
2601 })
2602 }
2603
2604 pub fn record(self) -> Option<Thing> {
2610 match self {
2611 Value::Object(mut v) => match v.remove("id") {
2613 Some(Value::Thing(v)) => Some(v),
2614 _ => None,
2615 },
2616 Value::Array(mut v) => match v.len() {
2618 1 => v.remove(0).record(),
2619 _ => None,
2620 },
2621 Value::Thing(v) => Some(v),
2623 _ => None,
2625 }
2626 }
2627
2628 pub(crate) fn jsonpath(&self) -> Idiom {
2634 self.to_raw_string()
2635 .as_str()
2636 .trim_start_matches('/')
2637 .split(&['.', '/'][..])
2638 .map(Part::from)
2639 .collect::<Vec<Part>>()
2640 .into()
2641 }
2642
2643 pub(crate) fn is_static(&self) -> bool {
2649 match self {
2650 Value::None => true,
2651 Value::Null => true,
2652 Value::Bool(_) => true,
2653 Value::Bytes(_) => true,
2654 Value::Uuid(_) => true,
2655 Value::Thing(_) => true,
2656 Value::Number(_) => true,
2657 Value::Strand(_) => true,
2658 Value::Duration(_) => true,
2659 Value::Datetime(_) => true,
2660 Value::Geometry(_) => true,
2661 Value::Array(v) => v.is_static(),
2662 Value::Object(v) => v.is_static(),
2663 Value::Expression(v) => v.is_static(),
2664 Value::Function(v) => v.is_static(),
2665 Value::Cast(v) => v.is_static(),
2666 Value::Constant(_) => true,
2667 _ => false,
2668 }
2669 }
2670
2671 pub fn equal(&self, other: &Value) -> bool {
2677 match self {
2678 Value::None => other.is_none(),
2679 Value::Null => other.is_null(),
2680 Value::Bool(v) => match other {
2681 Value::Bool(w) => v == w,
2682 _ => false,
2683 },
2684 Value::Uuid(v) => match other {
2685 Value::Uuid(w) => v == w,
2686 Value::Regex(w) => w.regex().is_match(v.to_raw().as_str()),
2687 _ => false,
2688 },
2689 Value::Thing(v) => match other {
2690 Value::Thing(w) => v == w,
2691 Value::Regex(w) => w.regex().is_match(v.to_raw().as_str()),
2692 _ => false,
2693 },
2694 Value::Strand(v) => match other {
2695 Value::Strand(w) => v == w,
2696 Value::Regex(w) => w.regex().is_match(v.as_str()),
2697 _ => false,
2698 },
2699 Value::Regex(v) => match other {
2700 Value::Regex(w) => v == w,
2701 Value::Uuid(w) => v.regex().is_match(w.to_raw().as_str()),
2702 Value::Thing(w) => v.regex().is_match(w.to_raw().as_str()),
2703 Value::Strand(w) => v.regex().is_match(w.as_str()),
2704 _ => false,
2705 },
2706 Value::Array(v) => match other {
2707 Value::Array(w) => v == w,
2708 _ => false,
2709 },
2710 Value::Object(v) => match other {
2711 Value::Object(w) => v == w,
2712 _ => false,
2713 },
2714 Value::Number(v) => match other {
2715 Value::Number(w) => v == w,
2716 _ => false,
2717 },
2718 Value::Geometry(v) => match other {
2719 Value::Geometry(w) => v == w,
2720 _ => false,
2721 },
2722 Value::Duration(v) => match other {
2723 Value::Duration(w) => v == w,
2724 _ => false,
2725 },
2726 Value::Datetime(v) => match other {
2727 Value::Datetime(w) => v == w,
2728 _ => false,
2729 },
2730 _ => self == other,
2731 }
2732 }
2733
2734 pub fn all_equal(&self, other: &Value) -> bool {
2736 match self {
2737 Value::Array(v) => v.iter().all(|v| v.equal(other)),
2738 _ => self.equal(other),
2739 }
2740 }
2741
2742 pub fn any_equal(&self, other: &Value) -> bool {
2744 match self {
2745 Value::Array(v) => v.iter().any(|v| v.equal(other)),
2746 _ => self.equal(other),
2747 }
2748 }
2749
2750 pub fn fuzzy(&self, other: &Value) -> bool {
2752 match self {
2753 Value::Uuid(v) => match other {
2754 Value::Strand(w) => v.to_raw().as_str().fuzzy_match(w.as_str()),
2755 _ => false,
2756 },
2757 Value::Strand(v) => match other {
2758 Value::Strand(w) => v.as_str().fuzzy_match(w.as_str()),
2759 _ => false,
2760 },
2761 _ => self.equal(other),
2762 }
2763 }
2764
2765 pub fn all_fuzzy(&self, other: &Value) -> bool {
2767 match self {
2768 Value::Array(v) => v.iter().all(|v| v.fuzzy(other)),
2769 _ => self.fuzzy(other),
2770 }
2771 }
2772
2773 pub fn any_fuzzy(&self, other: &Value) -> bool {
2775 match self {
2776 Value::Array(v) => v.iter().any(|v| v.fuzzy(other)),
2777 _ => self.fuzzy(other),
2778 }
2779 }
2780
2781 pub fn contains(&self, other: &Value) -> bool {
2783 match self {
2784 Value::Array(v) => v.iter().any(|v| v.equal(other)),
2785 Value::Uuid(v) => match other {
2786 Value::Strand(w) => v.to_raw().contains(w.as_str()),
2787 _ => false,
2788 },
2789 Value::Strand(v) => match other {
2790 Value::Strand(w) => v.contains(w.as_str()),
2791 _ => false,
2792 },
2793 Value::Geometry(v) => match other {
2794 Value::Geometry(w) => v.contains(w),
2795 _ => false,
2796 },
2797 Value::Object(v) => match other {
2798 Value::Strand(w) => v.0.contains_key(&w.0),
2799 _ => false,
2800 },
2801 Value::Range(r) => {
2802 let beg = match &r.beg {
2803 Bound::Unbounded => true,
2804 Bound::Included(beg) => beg.le(other),
2805 Bound::Excluded(beg) => beg.lt(other),
2806 };
2807
2808 beg && match &r.end {
2809 Bound::Unbounded => true,
2810 Bound::Included(end) => end.ge(other),
2811 Bound::Excluded(end) => end.gt(other),
2812 }
2813 }
2814 _ => false,
2815 }
2816 }
2817
2818 pub fn contains_all(&self, other: &Value) -> bool {
2820 match other {
2821 Value::Array(v) if v.iter().all(|v| v.is_strand()) && self.is_strand() => {
2822 let Value::Strand(this) = self else {
2824 return false;
2825 };
2826 v.iter().all(|s| {
2827 let Value::Strand(other_string) = s else {
2828 return false;
2829 };
2830 this.0.contains(&other_string.0)
2831 })
2832 }
2833 Value::Array(v) => v.iter().all(|v| match self {
2834 Value::Array(w) => w.iter().any(|w| v.equal(w)),
2835 Value::Geometry(_) => self.contains(v),
2836 _ => false,
2837 }),
2838 Value::Strand(other_strand) => match self {
2839 Value::Strand(s) => s.0.contains(&other_strand.0),
2840 _ => false,
2841 },
2842 _ => false,
2843 }
2844 }
2845
2846 pub fn contains_any(&self, other: &Value) -> bool {
2848 match other {
2849 Value::Array(v) if v.iter().all(|v| v.is_strand()) && self.is_strand() => {
2850 let Value::Strand(this) = self else {
2852 return false;
2853 };
2854 v.iter().any(|s| {
2855 let Value::Strand(other_string) = s else {
2856 return false;
2857 };
2858 this.0.contains(&other_string.0)
2859 })
2860 }
2861 Value::Array(v) => v.iter().any(|v| match self {
2862 Value::Array(w) => w.iter().any(|w| v.equal(w)),
2863 Value::Geometry(_) => self.contains(v),
2864 _ => false,
2865 }),
2866 Value::Strand(other_strand) => match self {
2867 Value::Strand(s) => s.0.contains(&other_strand.0),
2868 _ => false,
2869 },
2870 _ => false,
2871 }
2872 }
2873
2874 pub fn intersects(&self, other: &Value) -> bool {
2876 match self {
2877 Value::Geometry(v) => match other {
2878 Value::Geometry(w) => v.intersects(w),
2879 _ => false,
2880 },
2881 _ => false,
2882 }
2883 }
2884
2885 pub fn lexical_cmp(&self, other: &Value) -> Option<Ordering> {
2891 match (self, other) {
2892 (Value::Strand(a), Value::Strand(b)) => Some(lexicmp::lexical_cmp(a, b)),
2893 _ => self.partial_cmp(other),
2894 }
2895 }
2896
2897 pub fn natural_cmp(&self, other: &Value) -> Option<Ordering> {
2899 match (self, other) {
2900 (Value::Strand(a), Value::Strand(b)) => Some(lexicmp::natural_cmp(a, b)),
2901 _ => self.partial_cmp(other),
2902 }
2903 }
2904
2905 pub fn natural_lexical_cmp(&self, other: &Value) -> Option<Ordering> {
2907 match (self, other) {
2908 (Value::Strand(a), Value::Strand(b)) => Some(lexicmp::natural_lexical_cmp(a, b)),
2909 _ => self.partial_cmp(other),
2910 }
2911 }
2912
2913 pub fn can_be_range_bound(&self) -> bool {
2914 matches!(
2915 self,
2916 Value::None
2917 | Value::Null
2918 | Value::Array(_)
2919 | Value::Block(_)
2920 | Value::Bool(_)
2921 | Value::Datetime(_)
2922 | Value::Duration(_)
2923 | Value::Geometry(_)
2924 | Value::Number(_)
2925 | Value::Object(_)
2926 | Value::Param(_)
2927 | Value::Strand(_)
2928 | Value::Subquery(_)
2929 | Value::Table(_)
2930 | Value::Uuid(_)
2931 )
2932 }
2933}
2934
2935impl fmt::Display for Value {
2936 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2937 let mut f = Pretty::from(f);
2938 match self {
2939 Value::None => write!(f, "NONE"),
2940 Value::Null => write!(f, "NULL"),
2941 Value::Array(v) => write!(f, "{v}"),
2942 Value::Block(v) => write!(f, "{v}"),
2943 Value::Bool(v) => write!(f, "{v}"),
2944 Value::Bytes(v) => write!(f, "{v}"),
2945 Value::Cast(v) => write!(f, "{v}"),
2946 Value::Constant(v) => write!(f, "{v}"),
2947 Value::Datetime(v) => write!(f, "{v}"),
2948 Value::Duration(v) => write!(f, "{v}"),
2949 Value::Edges(v) => write!(f, "{v}"),
2950 Value::Expression(v) => write!(f, "{v}"),
2951 Value::Function(v) => write!(f, "{v}"),
2952 Value::Model(v) => write!(f, "{v}"),
2953 Value::Future(v) => write!(f, "{v}"),
2954 Value::Geometry(v) => write!(f, "{v}"),
2955 Value::Idiom(v) => write!(f, "{v}"),
2956 Value::Mock(v) => write!(f, "{v}"),
2957 Value::Number(v) => write!(f, "{v}"),
2958 Value::Object(v) => write!(f, "{v}"),
2959 Value::Param(v) => write!(f, "{v}"),
2960 Value::Range(v) => write!(f, "{v}"),
2961 Value::Regex(v) => write!(f, "{v}"),
2962 Value::Strand(v) => write!(f, "{v}"),
2963 Value::Query(v) => write!(f, "{v}"),
2964 Value::Subquery(v) => write!(f, "{v}"),
2965 Value::Table(v) => write!(f, "{v}"),
2966 Value::Thing(v) => write!(f, "{v}"),
2967 Value::Uuid(v) => write!(f, "{v}"),
2968 Value::Closure(v) => write!(f, "{v}"),
2969 Value::Refs(v) => write!(f, "{v}"),
2970 }
2971 }
2972}
2973
2974impl InfoStructure for Value {
2975 fn structure(self) -> Value {
2976 self.to_string().into()
2977 }
2978}
2979
2980impl Value {
2981 pub fn validate_computed(&self) -> Result<(), Error> {
2983 use Value::*;
2984 match self {
2985 None | Null | Bool(_) | Number(_) | Strand(_) | Duration(_) | Datetime(_) | Uuid(_)
2986 | Geometry(_) | Bytes(_) | Thing(_) => Ok(()),
2987 Array(a) => a.validate_computed(),
2988 Object(o) => o.validate_computed(),
2989 Range(r) => r.validate_computed(),
2990 _ => Err(Error::NonComputed),
2991 }
2992 }
2993}
2994
2995impl Value {
2996 pub(crate) fn writeable(&self) -> bool {
2998 match self {
2999 Value::Cast(v) => v.writeable(),
3000 Value::Block(v) => v.writeable(),
3001 Value::Idiom(v) => v.writeable(),
3002 Value::Array(v) => v.iter().any(Value::writeable),
3003 Value::Object(v) => v.iter().any(|(_, v)| v.writeable()),
3004 Value::Function(v) => v.writeable(),
3005 Value::Model(m) => m.args.iter().any(Value::writeable),
3006 Value::Subquery(v) => v.writeable(),
3007 Value::Expression(v) => v.writeable(),
3008 _ => false,
3009 }
3010 }
3011 pub(crate) async fn compute(
3013 &self,
3014 stk: &mut Stk,
3015 ctx: &Context,
3016 opt: &Options,
3017 doc: Option<&CursorDoc>,
3018 ) -> Result<Value, Error> {
3019 match self.compute_unbordered(stk, ctx, opt, doc).await {
3020 Err(Error::Return {
3021 value,
3022 }) => Ok(value),
3023 res => res,
3024 }
3025 }
3026 pub(crate) async fn compute_unbordered(
3028 &self,
3029 stk: &mut Stk,
3030 ctx: &Context,
3031 opt: &Options,
3032 doc: Option<&CursorDoc>,
3033 ) -> Result<Value, Error> {
3034 let opt = &opt.dive(1)?;
3036
3037 match self {
3038 Value::Cast(v) => v.compute(stk, ctx, opt, doc).await,
3039 Value::Thing(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
3040 Value::Block(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
3041 Value::Range(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
3042 Value::Param(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
3043 Value::Idiom(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
3044 Value::Array(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
3045 Value::Object(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
3046 Value::Future(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
3047 Value::Constant(v) => v.compute(),
3048 Value::Function(v) => v.compute(stk, ctx, opt, doc).await,
3049 Value::Model(v) => v.compute(stk, ctx, opt, doc).await,
3050 Value::Subquery(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
3051 Value::Expression(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
3052 Value::Edges(v) => stk.run(|stk| v.compute(stk, ctx, opt, doc)).await,
3053 Value::Refs(v) => v.compute(ctx, opt, doc).await,
3054 _ => Ok(self.to_owned()),
3055 }
3056 }
3057}
3058
3059pub(crate) trait TryAdd<Rhs = Self> {
3062 type Output;
3063 fn try_add(self, rhs: Rhs) -> Result<Self::Output, Error>;
3064}
3065
3066impl TryAdd for Value {
3067 type Output = Self;
3068 fn try_add(self, other: Self) -> Result<Self, Error> {
3069 Ok(match (self, other) {
3070 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_add(w)?),
3071 (Self::Strand(v), Self::Strand(w)) => Self::Strand(v.try_add(w)?),
3072 (Self::Datetime(v), Self::Duration(w)) => Self::Datetime(w.try_add(v)?),
3073 (Self::Duration(v), Self::Datetime(w)) => Self::Datetime(v.try_add(w)?),
3074 (Self::Duration(v), Self::Duration(w)) => Self::Duration(v.try_add(w)?),
3075 (v, w) => return Err(Error::TryAdd(v.to_raw_string(), w.to_raw_string())),
3076 })
3077 }
3078}
3079
3080pub(crate) trait TrySub<Rhs = Self> {
3083 type Output;
3084 fn try_sub(self, v: Rhs) -> Result<Self::Output, Error>;
3085}
3086
3087impl TrySub for Value {
3088 type Output = Self;
3089 fn try_sub(self, other: Self) -> Result<Self, Error> {
3090 Ok(match (self, other) {
3091 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_sub(w)?),
3092 (Self::Datetime(v), Self::Datetime(w)) => Self::Duration(v.try_sub(w)?),
3093 (Self::Datetime(v), Self::Duration(w)) => Self::Datetime(w.try_sub(v)?),
3094 (Self::Duration(v), Self::Datetime(w)) => Self::Datetime(v.try_sub(w)?),
3095 (Self::Duration(v), Self::Duration(w)) => Self::Duration(v.try_sub(w)?),
3096 (v, w) => return Err(Error::TrySub(v.to_raw_string(), w.to_raw_string())),
3097 })
3098 }
3099}
3100
3101pub(crate) trait TryMul<Rhs = Self> {
3104 type Output;
3105 fn try_mul(self, v: Self) -> Result<Self::Output, Error>;
3106}
3107
3108impl TryMul for Value {
3109 type Output = Self;
3110 fn try_mul(self, other: Self) -> Result<Self, Error> {
3111 Ok(match (self, other) {
3112 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_mul(w)?),
3113 (v, w) => return Err(Error::TryMul(v.to_raw_string(), w.to_raw_string())),
3114 })
3115 }
3116}
3117
3118pub(crate) trait TryDiv<Rhs = Self> {
3121 type Output;
3122 fn try_div(self, v: Self) -> Result<Self::Output, Error>;
3123}
3124
3125impl TryDiv for Value {
3126 type Output = Self;
3127 fn try_div(self, other: Self) -> Result<Self, Error> {
3128 Ok(match (self, other) {
3129 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_div(w)?),
3130 (v, w) => return Err(Error::TryDiv(v.to_raw_string(), w.to_raw_string())),
3131 })
3132 }
3133}
3134
3135pub(crate) trait TryFloatDiv<Rhs = Self> {
3138 type Output;
3139 fn try_float_div(self, v: Self) -> Result<Self::Output, Error>;
3140}
3141
3142impl TryFloatDiv for Value {
3143 type Output = Self;
3144 fn try_float_div(self, other: Self) -> Result<Self::Output, Error> {
3145 Ok(match (self, other) {
3146 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_float_div(w)?),
3147 (v, w) => return Err(Error::TryDiv(v.to_raw_string(), w.to_raw_string())),
3148 })
3149 }
3150}
3151
3152pub(crate) trait TryRem<Rhs = Self> {
3155 type Output;
3156 fn try_rem(self, v: Self) -> Result<Self::Output, Error>;
3157}
3158
3159impl TryRem for Value {
3160 type Output = Self;
3161 fn try_rem(self, other: Self) -> Result<Self, Error> {
3162 Ok(match (self, other) {
3163 (Self::Number(v), Self::Number(w)) => Self::Number(v.try_rem(w)?),
3164 (v, w) => return Err(Error::TryRem(v.to_raw_string(), w.to_raw_string())),
3165 })
3166 }
3167}
3168
3169pub(crate) trait TryPow<Rhs = Self> {
3172 type Output;
3173 fn try_pow(self, v: Self) -> Result<Self::Output, Error>;
3174}
3175
3176impl TryPow for Value {
3177 type Output = Self;
3178 fn try_pow(self, other: Self) -> Result<Self, Error> {
3179 Ok(match (self, other) {
3180 (Value::Number(v), Value::Number(w)) => Self::Number(v.try_pow(w)?),
3181 (v, w) => return Err(Error::TryPow(v.to_raw_string(), w.to_raw_string())),
3182 })
3183 }
3184}
3185
3186pub(crate) trait TryNeg<Rhs = Self> {
3189 type Output;
3190 fn try_neg(self) -> Result<Self::Output, Error>;
3191}
3192
3193impl TryNeg for Value {
3194 type Output = Self;
3195 fn try_neg(self) -> Result<Self, Error> {
3196 Ok(match self {
3197 Self::Number(n) => Self::Number(n.try_neg()?),
3198 v => return Err(Error::TryNeg(v.to_string())),
3199 })
3200 }
3201}
3202
3203#[cfg(test)]
3204mod tests {
3205
3206 use chrono::TimeZone;
3207
3208 use super::*;
3209 use crate::syn::Parse;
3210
3211 #[test]
3212 fn check_none() {
3213 assert!(Value::None.is_none());
3214 assert!(!Value::Null.is_none());
3215 assert!(!Value::from(1).is_none());
3216 }
3217
3218 #[test]
3219 fn check_null() {
3220 assert!(Value::Null.is_null());
3221 assert!(!Value::None.is_null());
3222 assert!(!Value::from(1).is_null());
3223 }
3224
3225 #[test]
3226 fn check_true() {
3227 assert!(!Value::None.is_true());
3228 assert!(Value::Bool(true).is_true());
3229 assert!(!Value::Bool(false).is_true());
3230 assert!(!Value::from(1).is_true());
3231 assert!(!Value::from("something").is_true());
3232 }
3233
3234 #[test]
3235 fn check_false() {
3236 assert!(!Value::None.is_false());
3237 assert!(!Value::Bool(true).is_false());
3238 assert!(Value::Bool(false).is_false());
3239 assert!(!Value::from(1).is_false());
3240 assert!(!Value::from("something").is_false());
3241 }
3242
3243 #[test]
3244 fn convert_truthy() {
3245 assert!(!Value::None.is_truthy());
3246 assert!(!Value::Null.is_truthy());
3247 assert!(Value::Bool(true).is_truthy());
3248 assert!(!Value::Bool(false).is_truthy());
3249 assert!(!Value::from(0).is_truthy());
3250 assert!(Value::from(1).is_truthy());
3251 assert!(Value::from(-1).is_truthy());
3252 assert!(Value::from(1.1).is_truthy());
3253 assert!(Value::from(-1.1).is_truthy());
3254 assert!(Value::from("true").is_truthy());
3255 assert!(Value::from("false").is_truthy());
3256 assert!(Value::from("falsey").is_truthy());
3257 assert!(Value::from("something").is_truthy());
3258 assert!(Value::from(Uuid::new()).is_truthy());
3259 assert!(Value::from(Utc.with_ymd_and_hms(1948, 12, 3, 0, 0, 0).unwrap()).is_truthy());
3260 }
3261
3262 #[test]
3263 fn convert_string() {
3264 assert_eq!(String::from("NONE"), Value::None.as_string());
3265 assert_eq!(String::from("NULL"), Value::Null.as_string());
3266 assert_eq!(String::from("true"), Value::Bool(true).as_string());
3267 assert_eq!(String::from("false"), Value::Bool(false).as_string());
3268 assert_eq!(String::from("0"), Value::from(0).as_string());
3269 assert_eq!(String::from("1"), Value::from(1).as_string());
3270 assert_eq!(String::from("-1"), Value::from(-1).as_string());
3271 assert_eq!(String::from("1.1f"), Value::from(1.1).as_string());
3272 assert_eq!(String::from("-1.1f"), Value::from(-1.1).as_string());
3273 assert_eq!(String::from("3"), Value::from("3").as_string());
3274 assert_eq!(String::from("true"), Value::from("true").as_string());
3275 assert_eq!(String::from("false"), Value::from("false").as_string());
3276 assert_eq!(String::from("something"), Value::from("something").as_string());
3277 }
3278
3279 #[test]
3280 fn check_size() {
3281 assert!(64 >= std::mem::size_of::<Value>(), "size of value too big");
3282 assert!(104 >= std::mem::size_of::<Error>());
3283 assert!(104 >= std::mem::size_of::<Result<Value, Error>>());
3284 assert!(24 >= std::mem::size_of::<crate::sql::number::Number>());
3285 assert!(24 >= std::mem::size_of::<crate::sql::strand::Strand>());
3286 assert!(16 >= std::mem::size_of::<crate::sql::duration::Duration>());
3287 assert!(12 >= std::mem::size_of::<crate::sql::datetime::Datetime>());
3288 assert!(24 >= std::mem::size_of::<crate::sql::array::Array>());
3289 assert!(24 >= std::mem::size_of::<crate::sql::object::Object>());
3290 assert!(48 >= std::mem::size_of::<crate::sql::geometry::Geometry>());
3291 assert!(24 >= std::mem::size_of::<crate::sql::param::Param>());
3292 assert!(24 >= std::mem::size_of::<crate::sql::idiom::Idiom>());
3293 assert!(24 >= std::mem::size_of::<crate::sql::table::Table>());
3294 assert!(56 >= std::mem::size_of::<crate::sql::thing::Thing>());
3295 assert!(40 >= std::mem::size_of::<crate::sql::mock::Mock>());
3296 assert!(32 >= std::mem::size_of::<crate::sql::regex::Regex>());
3297 }
3298
3299 #[test]
3300 fn check_serialize() {
3301 let enc: Vec<u8> = revision::to_vec(&Value::None).unwrap();
3302 assert_eq!(2, enc.len());
3303 let enc: Vec<u8> = revision::to_vec(&Value::Null).unwrap();
3304 assert_eq!(2, enc.len());
3305 let enc: Vec<u8> = revision::to_vec(&Value::Bool(true)).unwrap();
3306 assert_eq!(3, enc.len());
3307 let enc: Vec<u8> = revision::to_vec(&Value::Bool(false)).unwrap();
3308 assert_eq!(3, enc.len());
3309 let enc: Vec<u8> = revision::to_vec(&Value::from("test")).unwrap();
3310 assert_eq!(8, enc.len());
3311 let enc: Vec<u8> = revision::to_vec(&Value::parse("{ hello: 'world' }")).unwrap();
3312 assert_eq!(19, enc.len());
3313 let enc: Vec<u8> = revision::to_vec(&Value::parse("{ compact: true, schema: 0 }")).unwrap();
3314 assert_eq!(27, enc.len());
3315 }
3316
3317 #[test]
3318 fn serialize_deserialize() {
3319 let val = Value::parse(
3320 "{ test: { something: [1, 'two', null, test:tobie, { trueee: false, noneee: nulll }] } }",
3321 );
3322 let res = Value::parse(
3323 "{ test: { something: [1, 'two', null, test:tobie, { trueee: false, noneee: nulll }] } }",
3324 );
3325 let enc: Vec<u8> = revision::to_vec(&val).unwrap();
3326 let dec: Value = revision::from_slice(&enc).unwrap();
3327 assert_eq!(res, dec);
3328 }
3329
3330 #[test]
3331 fn test_value_from_vec_i32() {
3332 let vector: Vec<i32> = vec![1, 2, 3, 4, 5, 6];
3333 let value = Value::from(vector);
3334 assert!(matches!(value, Value::Array(Array(_))));
3335 }
3336
3337 #[test]
3338 fn test_value_from_vec_f32() {
3339 let vector: Vec<f32> = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
3340 let value = Value::from(vector);
3341 assert!(matches!(value, Value::Array(Array(_))));
3342 }
3343}