surrealdb_core/sql/value/
value.rs

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	// These value types are simple values which
94	// can be used in query responses sent to
95	// the client. They typically do not need to
96	// be computed, unless an un-computed value
97	// is present inside an Array or Object type.
98	// These types can also be used within indexes
99	// and sort according to their order below.
100	#[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	// These Value types are un-computed values
115	// and are not used in query responses sent
116	// to the client. These types need to be
117	// computed, in order to convert them into
118	// one of the simple types listed above.
119	// These types are first computed into a
120	// simple type before being used in indexes.
121	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	// Add new variants here
143}
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	// -----------------------------------
899	// Initial record value
900	// -----------------------------------
901
902	/// Create an empty Object Value
903	pub fn base() -> Self {
904		Value::Object(Object::default())
905	}
906
907	// -----------------------------------
908	// Builtin types
909	// -----------------------------------
910
911	/// Convert this Value to a Result
912	pub fn ok(self) -> Result<Value, Error> {
913		Ok(self)
914	}
915
916	/// Convert this Value to an Option
917	pub fn some(self) -> Option<Value> {
918		match self {
919			Value::None => None,
920			val => Some(val),
921		}
922	}
923
924	// -----------------------------------
925	// Simple value detection
926	// -----------------------------------
927
928	/// Check if this Value is NONE or NULL
929	pub fn is_none_or_null(&self) -> bool {
930		matches!(self, Value::None | Value::Null)
931	}
932
933	/// Check if this Value is NONE
934	pub fn is_none(&self) -> bool {
935		matches!(self, Value::None)
936	}
937
938	/// Check if this Value is NONE
939	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	/// Check if this Value is NULL
948	pub fn is_null(&self) -> bool {
949		matches!(self, Value::Null)
950	}
951
952	/// Check if this Value not NONE or NULL
953	pub fn is_some(&self) -> bool {
954		!self.is_none() && !self.is_null()
955	}
956
957	/// Check if this Value is a boolean value
958	pub fn is_bool(&self) -> bool {
959		matches!(self, Value::Bool(_))
960	}
961
962	/// Check if this Value is TRUE or 'true'
963	pub fn is_true(&self) -> bool {
964		matches!(self, Value::Bool(true))
965	}
966
967	/// Check if this Value is FALSE or 'false'
968	pub fn is_false(&self) -> bool {
969		matches!(self, Value::Bool(false))
970	}
971
972	/// Check if this Value is truthy
973	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	/// Check if this Value is a UUID
990	pub fn is_uuid(&self) -> bool {
991		matches!(self, Value::Uuid(_))
992	}
993
994	/// Check if this Value is a Thing
995	pub fn is_thing(&self) -> bool {
996		matches!(self, Value::Thing(_))
997	}
998
999	/// Check if this Value is a single Thing
1000	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	/// Check if this Value is a single Thing
1008	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	/// Check if this Value is a Mock
1019	pub fn is_mock(&self) -> bool {
1020		matches!(self, Value::Mock(_))
1021	}
1022
1023	/// Check if this Value is a Param
1024	pub fn is_param(&self) -> bool {
1025		matches!(self, Value::Param(_))
1026	}
1027
1028	/// Check if this Value is a Range
1029	pub fn is_range(&self) -> bool {
1030		matches!(self, Value::Range(_))
1031	}
1032
1033	/// Check if this Value is a Table
1034	pub fn is_table(&self) -> bool {
1035		matches!(self, Value::Table(_))
1036	}
1037
1038	/// Check if this Value is a Strand
1039	pub fn is_strand(&self) -> bool {
1040		matches!(self, Value::Strand(_))
1041	}
1042
1043	/// Check if this Value is a Query
1044	pub fn is_query(&self) -> bool {
1045		matches!(self, Value::Query(_))
1046	}
1047
1048	/// Check if this Value is a float Number
1049	pub fn is_bytes(&self) -> bool {
1050		matches!(self, Value::Bytes(_))
1051	}
1052
1053	/// Check if this Value is an Array
1054	pub fn is_array(&self) -> bool {
1055		matches!(self, Value::Array(_))
1056	}
1057
1058	/// Check if this Value is an Object
1059	pub fn is_object(&self) -> bool {
1060		matches!(self, Value::Object(_))
1061	}
1062
1063	/// Check if this Value is a Number
1064	pub fn is_number(&self) -> bool {
1065		matches!(self, Value::Number(_))
1066	}
1067
1068	/// Check if this Value is a Datetime
1069	pub fn is_datetime(&self) -> bool {
1070		matches!(self, Value::Datetime(_))
1071	}
1072
1073	/// Check if this Value is a Duration
1074	pub fn is_duration(&self) -> bool {
1075		matches!(self, Value::Duration(_))
1076	}
1077
1078	/// Check if this Value is a Thing
1079	pub fn is_record(&self) -> bool {
1080		matches!(self, Value::Thing(_))
1081	}
1082
1083	/// Check if this Value is a Closure
1084	pub fn is_closure(&self) -> bool {
1085		matches!(self, Value::Closure(_))
1086	}
1087
1088	/// Check if this Value is a Thing, and belongs to a certain table
1089	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	/// Check if this Value is a Geometry
1100	pub fn is_geometry(&self) -> bool {
1101		matches!(self, Value::Geometry(_))
1102	}
1103
1104	/// Check if this Value is an int Number
1105	pub fn is_int(&self) -> bool {
1106		matches!(self, Value::Number(Number::Int(_)))
1107	}
1108
1109	/// Check if this Value is a float Number
1110	pub fn is_float(&self) -> bool {
1111		matches!(self, Value::Number(Number::Float(_)))
1112	}
1113
1114	/// Check if this Value is a decimal Number
1115	pub fn is_decimal(&self) -> bool {
1116		matches!(self, Value::Number(Number::Decimal(_)))
1117	}
1118
1119	/// Check if this Value is a Number but is a NAN
1120	pub fn is_nan(&self) -> bool {
1121		matches!(self, Value::Number(v) if v.is_nan())
1122	}
1123
1124	/// Check if this Value is a Number and is an integer
1125	pub fn is_integer(&self) -> bool {
1126		matches!(self, Value::Number(v) if v.is_integer())
1127	}
1128
1129	/// Check if this Value is a Number and is positive
1130	pub fn is_positive(&self) -> bool {
1131		matches!(self, Value::Number(v) if v.is_positive())
1132	}
1133
1134	/// Check if this Value is a Number and is negative
1135	pub fn is_negative(&self) -> bool {
1136		matches!(self, Value::Number(v) if v.is_negative())
1137	}
1138
1139	/// Check if this Value is a Number and is zero or positive
1140	pub fn is_zero_or_positive(&self) -> bool {
1141		matches!(self, Value::Number(v) if v.is_zero_or_positive())
1142	}
1143
1144	/// Check if this Value is a Number and is zero or negative
1145	pub fn is_zero_or_negative(&self) -> bool {
1146		matches!(self, Value::Number(v) if v.is_zero_or_negative())
1147	}
1148
1149	/// Check if this Value is a Thing of a specific type
1150	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	/// Check if this Value is a Geometry of a specific type
1158	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	// -----------------------------------
1194	// Simple conversion of value
1195	// -----------------------------------
1196
1197	/// Convert this Value into a String
1198	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	/// Converts this Value into an unquoted String
1208	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	// -----------------------------------
1218	// Expensive conversion of value
1219	// -----------------------------------
1220
1221	/// Converts this Value into an unquoted String
1222	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	/// Converts this Value into a field name
1232	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	/// Returns if this value can be the start of a idiom production.
1245	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	/// Try to convert this Value into a set of JSONPatch operations
1266	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	/// Converts a `surrealdb::sq::Value` into a `serde_json::Value`
1284	///
1285	/// This converts certain types like `Thing` into their simpler formats
1286	/// instead of the format used internally by SurrealDB.
1287	pub fn into_json(self) -> Json {
1288		self.into()
1289	}
1290
1291	// -----------------------------------
1292	// Simple conversion of values
1293	// -----------------------------------
1294
1295	/// Treat a string as a table name
1296	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	// -----------------------------------
1304	// Simple output of value type
1305	// -----------------------------------
1306
1307	/// Treat a string as a table name
1308	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	// -----------------------------------
1337	// Simple type coercion of values
1338	// -----------------------------------
1339
1340	/// Try to coerce this value to the specified `Kind`
1341	pub(crate) fn coerce_to(self, kind: &Kind) -> Result<Value, Error> {
1342		// Attempt to convert to the desired type
1343		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		// Check for any conversion errors
1405		match res {
1406			// There was a conversion error
1407			Err(Error::CoerceTo {
1408				from,
1409				..
1410			}) => Err(Error::CoerceTo {
1411				from,
1412				into: kind.to_string(),
1413			}),
1414			// There was a different error
1415			Err(e) => Err(e),
1416			// Everything converted ok
1417			Ok(v) => Ok(v),
1418		}
1419	}
1420
1421	/// Try to coerce this value to an `i64`
1422	pub fn coerce_to_i64(self) -> Result<i64, Error> {
1423		match self {
1424			// Allow any int number
1425			Value::Number(Number::Int(v)) => Ok(v),
1426			// Attempt to convert an float number
1427			Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(v as i64),
1428			// Attempt to convert a decimal number
1429			Value::Number(Number::Decimal(v)) if v.is_integer() => match v.try_into() {
1430				// The Decimal can be represented as an i64
1431				Ok(v) => Ok(v),
1432				// The Decimal is out of bounds
1433				_ => Err(Error::CoerceTo {
1434					from: self,
1435					into: "i64".into(),
1436				}),
1437			},
1438			// Anything else raises an error
1439			_ => Err(Error::CoerceTo {
1440				from: self,
1441				into: "i64".into(),
1442			}),
1443		}
1444	}
1445
1446	/// Try to coerce this value to an `u64`
1447	pub(crate) fn coerce_to_u64(self) -> Result<u64, Error> {
1448		match self {
1449			// Allow any int number
1450			Value::Number(Number::Int(v)) => Ok(v as u64),
1451			// Attempt to convert an float number
1452			Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(v as u64),
1453			// Attempt to convert a decimal number
1454			Value::Number(Number::Decimal(v)) if v.is_integer() => match v.try_into() {
1455				// The Decimal can be represented as an u64
1456				Ok(v) => Ok(v),
1457				// The Decimal is out of bounds
1458				_ => Err(Error::CoerceTo {
1459					from: self,
1460					into: "u64".into(),
1461				}),
1462			},
1463			// Anything else raises an error
1464			_ => Err(Error::CoerceTo {
1465				from: self,
1466				into: "u64".into(),
1467			}),
1468		}
1469	}
1470
1471	/// Try to coerce this value to an `f64`
1472	pub(crate) fn coerce_to_f64(self) -> Result<f64, Error> {
1473		match self {
1474			// Allow any float number
1475			Value::Number(Number::Float(v)) => Ok(v),
1476			// Attempt to convert an int number
1477			Value::Number(Number::Int(v)) => Ok(v as f64),
1478			// Attempt to convert a decimal number
1479			Value::Number(Number::Decimal(v)) => match v.try_into() {
1480				// The Decimal can be represented as a f64
1481				Ok(v) => Ok(v),
1482				// This Decimal loses precision
1483				_ => Err(Error::CoerceTo {
1484					from: self,
1485					into: "f64".into(),
1486				}),
1487			},
1488			// Anything else raises an error
1489			_ => Err(Error::CoerceTo {
1490				from: self,
1491				into: "f64".into(),
1492			}),
1493		}
1494	}
1495
1496	/// Try to coerce this value to a Literal, returns a `Value` with the coerced value
1497	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	/// Try to coerce this value to a `null`
1509	pub(crate) fn coerce_to_null(self) -> Result<Value, Error> {
1510		match self {
1511			// Allow any null value
1512			Value::Null => Ok(Value::Null),
1513			// Anything else raises an error
1514			_ => Err(Error::CoerceTo {
1515				from: self,
1516				into: "null".into(),
1517			}),
1518		}
1519	}
1520
1521	/// Try to coerce this value to a `bool`
1522	pub(crate) fn coerce_to_bool(self) -> Result<bool, Error> {
1523		match self {
1524			// Allow any boolean value
1525			Value::Bool(v) => Ok(v),
1526			// Anything else raises an error
1527			_ => Err(Error::CoerceTo {
1528				from: self,
1529				into: "bool".into(),
1530			}),
1531		}
1532	}
1533
1534	/// Try to coerce this value to an integer `Number`
1535	pub(crate) fn coerce_to_int(self) -> Result<Number, Error> {
1536		match self {
1537			// Allow any int number
1538			Value::Number(v) if v.is_int() => Ok(v),
1539			// Attempt to convert an float number
1540			Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(Number::Int(v as i64)),
1541			// Attempt to convert a decimal number
1542			Value::Number(Number::Decimal(v)) if v.is_integer() => match v.to_i64() {
1543				// The Decimal can be represented as an Int
1544				Some(v) => Ok(Number::Int(v)),
1545				// The Decimal is out of bounds
1546				_ => Err(Error::CoerceTo {
1547					from: self,
1548					into: "int".into(),
1549				}),
1550			},
1551			// Anything else raises an error
1552			_ => Err(Error::CoerceTo {
1553				from: self,
1554				into: "int".into(),
1555			}),
1556		}
1557	}
1558
1559	/// Try to coerce this value to a float `Number`
1560	pub(crate) fn coerce_to_float(self) -> Result<Number, Error> {
1561		match self {
1562			// Allow any float number
1563			Value::Number(v) if v.is_float() => Ok(v),
1564			// Attempt to convert an int number
1565			Value::Number(Number::Int(v)) => Ok(Number::Float(v as f64)),
1566			// Attempt to convert a decimal number
1567			Value::Number(Number::Decimal(ref v)) => match v.to_f64() {
1568				// The Decimal can be represented as a Float
1569				Some(v) => Ok(Number::Float(v)),
1570				// This BigDecimal loses precision
1571				None => Err(Error::CoerceTo {
1572					from: self,
1573					into: "float".into(),
1574				}),
1575			},
1576			// Anything else raises an error
1577			_ => Err(Error::CoerceTo {
1578				from: self,
1579				into: "float".into(),
1580			}),
1581		}
1582	}
1583
1584	/// Try to coerce this value to a decimal `Number`
1585	pub(crate) fn coerce_to_decimal(self) -> Result<Number, Error> {
1586		match self {
1587			// Allow any decimal number
1588			Value::Number(v) if v.is_decimal() => Ok(v),
1589			// Attempt to convert an int number
1590			Value::Number(Number::Int(v)) => match Decimal::from_i64(v) {
1591				// The Int can be represented as a Decimal
1592				Some(v) => Ok(Number::Decimal(v)),
1593				// This Int does not convert to a Decimal
1594				None => Err(Error::CoerceTo {
1595					from: self,
1596					into: "decimal".into(),
1597				}),
1598			},
1599			// Attempt to convert an float number
1600			Value::Number(Number::Float(v)) => match Decimal::from_f64(v) {
1601				// The Float can be represented as a Decimal
1602				Some(v) => Ok(Number::Decimal(v)),
1603				// This Float does not convert to a Decimal
1604				None => Err(Error::CoerceTo {
1605					from: self,
1606					into: "decimal".into(),
1607				}),
1608			},
1609			// Anything else raises an error
1610			_ => Err(Error::CoerceTo {
1611				from: self,
1612				into: "decimal".into(),
1613			}),
1614		}
1615	}
1616
1617	/// Try to coerce this value to a `Number`
1618	pub(crate) fn coerce_to_number(self) -> Result<Number, Error> {
1619		match self {
1620			// Allow any number
1621			Value::Number(v) => Ok(v),
1622			// Anything else raises an error
1623			_ => Err(Error::CoerceTo {
1624				from: self,
1625				into: "number".into(),
1626			}),
1627		}
1628	}
1629
1630	/// Try to coerce this value to a `Regex`
1631	pub(crate) fn coerce_to_regex(self) -> Result<Regex, Error> {
1632		match self {
1633			// Allow any Regex value
1634			Value::Regex(v) => Ok(v),
1635			// Allow any string value
1636			Value::Strand(v) => Ok(v.as_str().parse()?),
1637			// Anything else raises an error
1638			_ => Err(Error::CoerceTo {
1639				from: self,
1640				into: "regex".into(),
1641			}),
1642		}
1643	}
1644
1645	/// Try to coerce this value to a `String`
1646	pub(crate) fn coerce_to_string(self) -> Result<String, Error> {
1647		match self {
1648			// Allow any uuid value
1649			Value::Uuid(v) => Ok(v.to_raw()),
1650			// Allow any datetime value
1651			Value::Datetime(v) => Ok(v.to_raw()),
1652			// Allow any string value
1653			Value::Strand(v) => Ok(v.as_string()),
1654			// Anything else raises an error
1655			_ => Err(Error::CoerceTo {
1656				from: self,
1657				into: "string".into(),
1658			}),
1659		}
1660	}
1661
1662	/// Try to coerce this value to a `Strand`
1663	pub(crate) fn coerce_to_strand(self) -> Result<Strand, Error> {
1664		match self {
1665			// Allow any uuid value
1666			Value::Uuid(v) => Ok(v.to_raw().into()),
1667			// Allow any datetime value
1668			Value::Datetime(v) => Ok(v.to_raw().into()),
1669			// Allow any string value
1670			Value::Strand(v) => Ok(v),
1671			// Anything else raises an error
1672			_ => Err(Error::CoerceTo {
1673				from: self,
1674				into: "string".into(),
1675			}),
1676		}
1677	}
1678
1679	/// Try to coerce this value to a `Uuid`
1680	pub(crate) fn coerce_to_uuid(self) -> Result<Uuid, Error> {
1681		match self {
1682			// Uuids are allowed
1683			Value::Uuid(v) => Ok(v),
1684			// Anything else raises an error
1685			_ => Err(Error::CoerceTo {
1686				from: self,
1687				into: "uuid".into(),
1688			}),
1689		}
1690	}
1691
1692	/// Try to coerce this value to a `Closure`
1693	pub(crate) fn coerce_to_function(self) -> Result<Closure, Error> {
1694		match self {
1695			// Closures are allowed
1696			Value::Closure(v) => Ok(*v),
1697			// Anything else raises an error
1698			_ => Err(Error::CoerceTo {
1699				from: self,
1700				into: "function".into(),
1701			}),
1702		}
1703	}
1704
1705	/// Try to coerce this value to a `Datetime`
1706	pub(crate) fn coerce_to_datetime(self) -> Result<Datetime, Error> {
1707		match self {
1708			// Datetimes are allowed
1709			Value::Datetime(v) => Ok(v),
1710			// Anything else raises an error
1711			_ => Err(Error::CoerceTo {
1712				from: self,
1713				into: "datetime".into(),
1714			}),
1715		}
1716	}
1717
1718	/// Try to coerce this value to a `Duration`
1719	pub(crate) fn coerce_to_duration(self) -> Result<Duration, Error> {
1720		match self {
1721			// Durations are allowed
1722			Value::Duration(v) => Ok(v),
1723			// Anything else raises an error
1724			_ => Err(Error::CoerceTo {
1725				from: self,
1726				into: "duration".into(),
1727			}),
1728		}
1729	}
1730
1731	/// Try to coerce this value to a `Bytes`
1732	pub(crate) fn coerce_to_bytes(self) -> Result<Bytes, Error> {
1733		match self {
1734			// Bytes are allowed
1735			Value::Bytes(v) => Ok(v),
1736			// Anything else raises an error
1737			_ => Err(Error::CoerceTo {
1738				from: self,
1739				into: "bytes".into(),
1740			}),
1741		}
1742	}
1743
1744	/// Try to coerce this value to an `Object`
1745	pub(crate) fn coerce_to_object(self) -> Result<Object, Error> {
1746		match self {
1747			// Objects are allowed
1748			Value::Object(v) => Ok(v),
1749			// Anything else raises an error
1750			_ => Err(Error::CoerceTo {
1751				from: self,
1752				into: "object".into(),
1753			}),
1754		}
1755	}
1756
1757	/// Try to coerce this value to an `Array`
1758	pub(crate) fn coerce_to_array(self) -> Result<Array, Error> {
1759		match self {
1760			// Arrays are allowed
1761			Value::Array(v) => Ok(v),
1762			// Anything else raises an error
1763			_ => Err(Error::CoerceTo {
1764				from: self,
1765				into: "array".into(),
1766			}),
1767		}
1768	}
1769
1770	/// Try to coerce this value to a `Range`
1771	pub(crate) fn coerce_to_range(self) -> Result<Range, Error> {
1772		match self {
1773			// Ranges are allowed
1774			Value::Range(v) => Ok(*v),
1775			// Anything else raises an error
1776			_ => Err(Error::CoerceTo {
1777				from: self,
1778				into: "range".into(),
1779			}),
1780		}
1781	}
1782
1783	/// Try to coerce this value to an `Geometry` point
1784	pub(crate) fn coerce_to_point(self) -> Result<Geometry, Error> {
1785		match self {
1786			// Geometry points are allowed
1787			Value::Geometry(Geometry::Point(v)) => Ok(v.into()),
1788			// Anything else raises an error
1789			_ => Err(Error::CoerceTo {
1790				from: self,
1791				into: "point".into(),
1792			}),
1793		}
1794	}
1795
1796	/// Try to coerce this value to a Record or `Thing`
1797	pub(crate) fn coerce_to_record(self) -> Result<Thing, Error> {
1798		match self {
1799			// Records are allowed
1800			Value::Thing(v) => Ok(v),
1801			// Anything else raises an error
1802			_ => Err(Error::CoerceTo {
1803				from: self,
1804				into: "record".into(),
1805			}),
1806		}
1807	}
1808
1809	/// Try to coerce this value to an `Geometry` type
1810	pub(crate) fn coerce_to_geometry(self) -> Result<Geometry, Error> {
1811		match self {
1812			// Geometries are allowed
1813			Value::Geometry(v) => Ok(v),
1814			// Anything else raises an error
1815			_ => Err(Error::CoerceTo {
1816				from: self,
1817				into: "geometry".into(),
1818			}),
1819		}
1820	}
1821
1822	/// Try to coerce this value to a Record of a certain type
1823	pub(crate) fn coerce_to_record_type(self, val: &[Table]) -> Result<Thing, Error> {
1824		match self {
1825			// Records are allowed if correct type
1826			Value::Thing(v) if self.is_record_type(val) => Ok(v),
1827			// Anything else raises an error
1828			_ => Err(Error::CoerceTo {
1829				from: self,
1830				into: "record".into(),
1831			}),
1832		}
1833	}
1834
1835	/// Try to coerce this value to a `Geometry` of a certain type
1836	pub(crate) fn coerce_to_geometry_type(self, val: &[String]) -> Result<Geometry, Error> {
1837		match self {
1838			// Geometries are allowed if correct type
1839			Value::Geometry(v) if self.is_geometry_type(val) => Ok(v),
1840			// Anything else raises an error
1841			_ => Err(Error::CoerceTo {
1842				from: self,
1843				into: "geometry".into(),
1844			}),
1845		}
1846	}
1847
1848	/// Try to coerce this value to an `Array` of a certain type
1849	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	/// Try to coerce this value to an `Array` of a certain type, and length
1867	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	/// Try to coerce this value to an `Array` of a certain type, unique values
1892	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	/// Try to coerce this value to an `Array` of a certain type, unique values, and length
1911	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	// -----------------------------------
1937	// Advanced type conversion of values
1938	// -----------------------------------
1939
1940	/// Try to convert this value to the specified `Kind`
1941	pub(crate) fn convert_to(self, kind: &Kind) -> Result<Value, Error> {
1942		// Attempt to convert to the desired type
1943		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		// Check for any conversion errors
2005		match res {
2006			// There was a conversion error
2007			Err(Error::ConvertTo {
2008				from,
2009				..
2010			}) => Err(Error::ConvertTo {
2011				from,
2012				into: kind.to_string(),
2013			}),
2014			// There was a different error
2015			Err(e) => Err(e),
2016			// Everything converted ok
2017			Ok(v) => Ok(v),
2018		}
2019	}
2020
2021	/// Try to convert this value to a Literal, returns a `Value` with the coerced value
2022	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	/// Try to convert this value to a `null`
2034	pub(crate) fn convert_to_null(self) -> Result<Value, Error> {
2035		match self {
2036			// Allow any boolean value
2037			Value::Null => Ok(Value::Null),
2038			// Anything else raises an error
2039			_ => Err(Error::ConvertTo {
2040				from: self,
2041				into: "null".into(),
2042			}),
2043		}
2044	}
2045
2046	/// Try to convert this value to a `bool`
2047	pub(crate) fn convert_to_bool(self) -> Result<bool, Error> {
2048		match self {
2049			// Allow any boolean value
2050			Value::Bool(v) => Ok(v),
2051			// Attempt to convert a string value
2052			Value::Strand(ref v) => match v.parse::<bool>() {
2053				// The string can be parsed as a Float
2054				Ok(v) => Ok(v),
2055				// This string is not a float
2056				_ => Err(Error::ConvertTo {
2057					from: self,
2058					into: "bool".into(),
2059				}),
2060			},
2061			// Anything else raises an error
2062			_ => Err(Error::ConvertTo {
2063				from: self,
2064				into: "bool".into(),
2065			}),
2066		}
2067	}
2068
2069	/// Try to convert this value to an integer `Number`
2070	pub(crate) fn convert_to_int(self) -> Result<Number, Error> {
2071		match self {
2072			// Allow any int number
2073			Value::Number(v) if v.is_int() => Ok(v),
2074			// Attempt to convert an float number
2075			Value::Number(Number::Float(v)) if v.fract() == 0.0 => Ok(Number::Int(v as i64)),
2076			// Attempt to convert a decimal number
2077			Value::Number(Number::Decimal(v)) if v.is_integer() => match v.try_into() {
2078				// The Decimal can be parsed as an Int
2079				Ok(v) => Ok(Number::Int(v)),
2080				// The Decimal is out of bounds
2081				_ => Err(Error::ConvertTo {
2082					from: self,
2083					into: "int".into(),
2084				}),
2085			},
2086			// Attempt to convert a string value
2087			Value::Strand(ref v) => match v.parse::<i64>() {
2088				// The string can be parsed as a Float
2089				Ok(v) => Ok(Number::Int(v)),
2090				// This string is not a float
2091				_ => Err(Error::ConvertTo {
2092					from: self,
2093					into: "int".into(),
2094				}),
2095			},
2096			// Anything else raises an error
2097			_ => Err(Error::ConvertTo {
2098				from: self,
2099				into: "int".into(),
2100			}),
2101		}
2102	}
2103
2104	/// Try to convert this value to a float `Number`
2105	pub(crate) fn convert_to_float(self) -> Result<Number, Error> {
2106		match self {
2107			// Allow any float number
2108			Value::Number(v) if v.is_float() => Ok(v),
2109			// Attempt to convert an int number
2110			Value::Number(Number::Int(v)) => Ok(Number::Float(v as f64)),
2111			// Attempt to convert a decimal number
2112			Value::Number(Number::Decimal(v)) => match v.try_into() {
2113				// The Decimal can be parsed as a Float
2114				Ok(v) => Ok(Number::Float(v)),
2115				// The Decimal loses precision
2116				_ => Err(Error::ConvertTo {
2117					from: self,
2118					into: "float".into(),
2119				}),
2120			},
2121			// Attempt to convert a string value
2122			Value::Strand(ref v) => match v.parse::<f64>() {
2123				// The string can be parsed as a Float
2124				Ok(v) => Ok(Number::Float(v)),
2125				// This string is not a float
2126				_ => Err(Error::ConvertTo {
2127					from: self,
2128					into: "float".into(),
2129				}),
2130			},
2131			// Anything else raises an error
2132			_ => Err(Error::ConvertTo {
2133				from: self,
2134				into: "float".into(),
2135			}),
2136		}
2137	}
2138
2139	/// Try to convert this value to a decimal `Number`
2140	pub(crate) fn convert_to_decimal(self) -> Result<Number, Error> {
2141		match self {
2142			// Allow any decimal number
2143			Value::Number(v) if v.is_decimal() => Ok(v),
2144			// Attempt to convert an int number
2145			Value::Number(Number::Int(ref v)) => Ok(Number::Decimal(Decimal::from(*v))),
2146			// Attempt to convert an float number
2147			Value::Number(Number::Float(ref v)) => match Decimal::try_from(*v) {
2148				// The Float can be represented as a Decimal
2149				Ok(v) => Ok(Number::Decimal(v)),
2150				// This Float does not convert to a Decimal
2151				_ => Err(Error::ConvertTo {
2152					from: self,
2153					into: "decimal".into(),
2154				}),
2155			},
2156			// Attempt to convert a string value
2157			Value::Strand(ref v) => match Decimal::from_str(v) {
2158				// The string can be parsed as a Decimal
2159				Ok(v) => Ok(Number::Decimal(v)),
2160				// This string is not a Decimal
2161				_ => Err(Error::ConvertTo {
2162					from: self,
2163					into: "decimal".into(),
2164				}),
2165			},
2166			// Anything else raises an error
2167			_ => Err(Error::ConvertTo {
2168				from: self,
2169				into: "decimal".into(),
2170			}),
2171		}
2172	}
2173
2174	/// Try to convert this value to a `Number`
2175	pub(crate) fn convert_to_number(self) -> Result<Number, Error> {
2176		match self {
2177			// Allow any number
2178			Value::Number(v) => Ok(v),
2179			// Attempt to convert a string value
2180			Value::Strand(ref v) => match Number::from_str(v) {
2181				// The string can be parsed as a number
2182				Ok(v) => Ok(v),
2183				// This string is not a float
2184				_ => Err(Error::ConvertTo {
2185					from: self,
2186					into: "number".into(),
2187				}),
2188			},
2189			// Anything else raises an error
2190			_ => Err(Error::ConvertTo {
2191				from: self,
2192				into: "number".into(),
2193			}),
2194		}
2195	}
2196
2197	/// Try to convert this value to a `String`
2198	pub fn convert_to_string(self) -> Result<String, Error> {
2199		match self {
2200			// Bytes can't convert to strings
2201			Value::Bytes(_) => Err(Error::ConvertTo {
2202				from: self,
2203				into: "string".into(),
2204			}),
2205			// None can't convert to a string
2206			Value::None => Err(Error::ConvertTo {
2207				from: self,
2208				into: "string".into(),
2209			}),
2210			// Null can't convert to a string
2211			Value::Null => Err(Error::ConvertTo {
2212				from: self,
2213				into: "string".into(),
2214			}),
2215			// Stringify anything else
2216			_ => Ok(self.as_string()),
2217		}
2218	}
2219
2220	/// Try to convert this value to a `Strand`
2221	pub(crate) fn convert_to_strand(self) -> Result<Strand, Error> {
2222		match self {
2223			// Bytes can't convert to strings
2224			Value::Bytes(_) => Err(Error::ConvertTo {
2225				from: self,
2226				into: "string".into(),
2227			}),
2228			// None can't convert to a string
2229			Value::None => Err(Error::ConvertTo {
2230				from: self,
2231				into: "string".into(),
2232			}),
2233			// Null can't convert to a string
2234			Value::Null => Err(Error::ConvertTo {
2235				from: self,
2236				into: "string".into(),
2237			}),
2238			// Allow any string value
2239			Value::Strand(v) => Ok(v),
2240			// Stringify anything else
2241			Value::Uuid(v) => Ok(v.to_raw().into()),
2242			// Stringify anything else
2243			Value::Datetime(v) => Ok(v.to_raw().into()),
2244			// Stringify anything else
2245			_ => Ok(self.to_string().into()),
2246		}
2247	}
2248
2249	/// Try to convert this value to a `Uuid`
2250	pub(crate) fn convert_to_uuid(self) -> Result<Uuid, Error> {
2251		match self {
2252			// Uuids are allowed
2253			Value::Uuid(v) => Ok(v),
2254			// Attempt to parse a string
2255			Value::Strand(ref v) => match Uuid::from_str(v) {
2256				// The string can be parsed as a uuid
2257				Ok(v) => Ok(v),
2258				// This string is not a uuid
2259				_ => Err(Error::ConvertTo {
2260					from: self,
2261					into: "uuid".into(),
2262				}),
2263			},
2264			// Anything else raises an error
2265			_ => Err(Error::ConvertTo {
2266				from: self,
2267				into: "uuid".into(),
2268			}),
2269		}
2270	}
2271
2272	/// Try to convert this value to a `Uuid`
2273	pub(crate) fn convert_to_regex(self) -> Result<Regex, Error> {
2274		match self {
2275			// Uuids are allowed
2276			Value::Regex(v) => Ok(v),
2277			// Attempt to parse a string
2278			Value::Strand(ref v) => match Regex::from_str(v) {
2279				// The string can be parsed as a uuid
2280				Ok(v) => Ok(v),
2281				// This string is not a uuid
2282				_ => Err(Error::ConvertTo {
2283					from: self,
2284					into: "regex".into(),
2285				}),
2286			},
2287			// Anything else raises an error
2288			_ => Err(Error::ConvertTo {
2289				from: self,
2290				into: "regex".into(),
2291			}),
2292		}
2293	}
2294
2295	/// Try to convert this value to a `Closure`
2296	pub(crate) fn convert_to_function(self) -> Result<Closure, Error> {
2297		match self {
2298			// Closures are allowed
2299			Value::Closure(v) => Ok(*v),
2300			// Anything else converts to a closure with self as the body
2301			_ => Err(Error::ConvertTo {
2302				from: self,
2303				into: "function".into(),
2304			}),
2305		}
2306	}
2307
2308	/// Try to convert this value to a `Datetime`
2309	pub(crate) fn convert_to_datetime(self) -> Result<Datetime, Error> {
2310		match self {
2311			// Datetimes are allowed
2312			Value::Datetime(v) => Ok(v),
2313			// Attempt to parse a string
2314			Value::Strand(ref v) => match Datetime::from_str(v) {
2315				// The string can be parsed as a datetime
2316				Ok(v) => Ok(v),
2317				// This string is not a datetime
2318				_ => Err(Error::ConvertTo {
2319					from: self,
2320					into: "datetime".into(),
2321				}),
2322			},
2323			// Anything else raises an error
2324			_ => Err(Error::ConvertTo {
2325				from: self,
2326				into: "datetime".into(),
2327			}),
2328		}
2329	}
2330
2331	/// Try to convert this value to a `Duration`
2332	pub(crate) fn convert_to_duration(self) -> Result<Duration, Error> {
2333		match self {
2334			// Durations are allowed
2335			Value::Duration(v) => Ok(v),
2336			// Attempt to parse a string
2337			Value::Strand(ref v) => match Duration::from_str(v) {
2338				// The string can be parsed as a duration
2339				Ok(v) => Ok(v),
2340				// This string is not a duration
2341				_ => Err(Error::ConvertTo {
2342					from: self,
2343					into: "duration".into(),
2344				}),
2345			},
2346			// Anything else raises an error
2347			_ => Err(Error::ConvertTo {
2348				from: self,
2349				into: "duration".into(),
2350			}),
2351		}
2352	}
2353
2354	/// Try to convert this value to a `Bytes`
2355	pub(crate) fn convert_to_bytes(self) -> Result<Bytes, Error> {
2356		match self {
2357			// Bytes are allowed
2358			Value::Bytes(v) => Ok(v),
2359			// Strings can be converted to bytes
2360			Value::Strand(s) => Ok(Bytes(s.0.into_bytes())),
2361			// Anything else raises an error
2362			_ => Err(Error::ConvertTo {
2363				from: self,
2364				into: "bytes".into(),
2365			}),
2366		}
2367	}
2368
2369	/// Try to convert this value to an `Object`
2370	pub(crate) fn convert_to_object(self) -> Result<Object, Error> {
2371		match self {
2372			// Objects are allowed
2373			Value::Object(v) => Ok(v),
2374			// Anything else raises an error
2375			_ => Err(Error::ConvertTo {
2376				from: self,
2377				into: "object".into(),
2378			}),
2379		}
2380	}
2381
2382	/// Try to convert this value to an `Array`
2383	pub(crate) fn convert_to_array(self) -> Result<Array, Error> {
2384		match self {
2385			// Arrays are allowed
2386			Value::Array(v) => Ok(v),
2387			// Ranges convert to an array
2388			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			// Anything else raises an error
2393			_ => Err(Error::ConvertTo {
2394				from: self,
2395				into: "array".into(),
2396			}),
2397		}
2398	}
2399
2400	/// Try to convert this value to a `Range`
2401	pub(crate) fn convert_to_range(self) -> Result<Range, Error> {
2402		match self {
2403			// Ranges are allowed
2404			Value::Range(r) => Ok(*r),
2405			// Arrays with two elements are allowed
2406			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			// Anything else raises an error
2414			_ => Err(Error::ConvertTo {
2415				from: self,
2416				into: "range".into(),
2417			}),
2418		}
2419	}
2420
2421	/// Try to convert this value to an `Geometry` point
2422	pub(crate) fn convert_to_point(self) -> Result<Geometry, Error> {
2423		match self {
2424			// Geometry points are allowed
2425			Value::Geometry(Geometry::Point(v)) => Ok(v.into()),
2426			// An array of two floats are allowed
2427			Value::Array(ref v) if v.len() == 2 => match v.as_slice() {
2428				// The array can be represented as a point
2429				[Value::Number(v), Value::Number(w)] => Ok((v.to_float(), w.to_float()).into()),
2430				// The array is not a geometry point
2431				_ => Err(Error::ConvertTo {
2432					from: self,
2433					into: "point".into(),
2434				}),
2435			},
2436			// Anything else raises an error
2437			_ => Err(Error::ConvertTo {
2438				from: self,
2439				into: "point".into(),
2440			}),
2441		}
2442	}
2443
2444	/// Try to convert this value to a Record or `Thing`
2445	pub(crate) fn convert_to_record(self) -> Result<Thing, Error> {
2446		match self {
2447			// Records are allowed
2448			Value::Thing(v) => Ok(v),
2449			// Attempt to parse a string
2450			Value::Strand(ref v) => match Thing::from_str(v) {
2451				// The string can be parsed as a record
2452				Ok(v) => Ok(v),
2453				// This string is not a record
2454				_ => Err(Error::ConvertTo {
2455					from: self,
2456					into: "record".into(),
2457				}),
2458			},
2459			// Anything else raises an error
2460			_ => Err(Error::ConvertTo {
2461				from: self,
2462				into: "record".into(),
2463			}),
2464		}
2465	}
2466
2467	/// Try to convert this value to an `Geometry` type
2468	pub(crate) fn convert_to_geometry(self) -> Result<Geometry, Error> {
2469		match self {
2470			// Geometries are allowed
2471			Value::Geometry(v) => Ok(v),
2472			// Anything else raises an error
2473			_ => Err(Error::ConvertTo {
2474				from: self,
2475				into: "geometry".into(),
2476			}),
2477		}
2478	}
2479
2480	/// Try to convert this value to a Record of a certain type
2481	pub(crate) fn convert_to_record_type(self, val: &[Table]) -> Result<Thing, Error> {
2482		match self {
2483			// Records are allowed if correct type
2484			Value::Thing(v) if self.is_record_type(val) => Ok(v),
2485			// Attempt to parse a string
2486			Value::Strand(ref v) => match Thing::from_str(v) {
2487				// The string can be parsed as a record of this type
2488				Ok(v) if v.is_record_type(val) => Ok(v),
2489				// This string is not a record of this type
2490				_ => Err(Error::ConvertTo {
2491					from: self,
2492					into: "record".into(),
2493				}),
2494			},
2495			// Anything else raises an error
2496			_ => Err(Error::ConvertTo {
2497				from: self,
2498				into: "record".into(),
2499			}),
2500		}
2501	}
2502
2503	/// Try to convert this value to a `Geometry` of a certain type
2504	pub(crate) fn convert_to_geometry_type(self, val: &[String]) -> Result<Geometry, Error> {
2505		match self {
2506			// Geometries are allowed if correct type
2507			Value::Geometry(v) if self.is_geometry_type(val) => Ok(v),
2508			// Anything else raises an error
2509			_ => Err(Error::ConvertTo {
2510				from: self,
2511				into: "geometry".into(),
2512			}),
2513		}
2514	}
2515
2516	/// Try to convert this value to ab `Array` of a certain type
2517	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	/// Try to convert this value to ab `Array` of a certain type and length
2535	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	/// Try to convert this value to an `Array` of a certain type, unique values
2560	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	/// Try to convert this value to an `Array` of a certain type, unique values, and length
2579	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	// -----------------------------------
2605	// Record ID extraction
2606	// -----------------------------------
2607
2608	/// Fetch the record id if there is one
2609	pub fn record(self) -> Option<Thing> {
2610		match self {
2611			// This is an object so look for the id field
2612			Value::Object(mut v) => match v.remove("id") {
2613				Some(Value::Thing(v)) => Some(v),
2614				_ => None,
2615			},
2616			// This is an array so take the first item
2617			Value::Array(mut v) => match v.len() {
2618				1 => v.remove(0).record(),
2619				_ => None,
2620			},
2621			// This is a record id already
2622			Value::Thing(v) => Some(v),
2623			// There is no valid record id
2624			_ => None,
2625		}
2626	}
2627
2628	// -----------------------------------
2629	// JSON Path conversion
2630	// -----------------------------------
2631
2632	/// Converts this Value into a JSONPatch path
2633	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	// -----------------------------------
2644	// JSON Path conversion
2645	// -----------------------------------
2646
2647	/// Checks whether this value is a static value
2648	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	// -----------------------------------
2672	// Value operations
2673	// -----------------------------------
2674
2675	/// Check if this Value is equal to another Value
2676	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	/// Check if all Values in an Array are equal to another Value
2735	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	/// Check if any Values in an Array are equal to another Value
2743	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	/// Fuzzy check if this Value is equal to another Value
2751	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	/// Fuzzy check if all Values in an Array are equal to another Value
2766	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	/// Fuzzy check if any Values in an Array are equal to another Value
2774	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	/// Check if this Value contains another Value
2782	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	/// Check if all Values in an Array contain another Value
2819	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				// confirmed as strand so all return false is unreachable
2823				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	/// Check if any Values in an Array contain another Value
2847	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				// confirmed as strand so all return false is unreachable
2851				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	/// Check if this Value intersects another Value
2875	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	// -----------------------------------
2886	// Sorting operations
2887	// -----------------------------------
2888
2889	/// Compare this Value to another Value lexicographically
2890	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	/// Compare this Value to another Value using natural numerical comparison
2898	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	/// Compare this Value to another Value lexicographically and using natural numerical comparison
2906	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	/// Validate that a Value is computed or contains only computed Values
2982	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	/// Check if we require a writeable transaction
2997	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	/// Process this type returning a computed simple Value
3012	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	/// Process this type returning a computed simple Value, without catching errors
3027	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		// Prevent infinite recursion due to casting, expressions, etc.
3035		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
3059// ------------------------------
3060
3061pub(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
3080// ------------------------------
3081
3082pub(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
3101// ------------------------------
3102
3103pub(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
3118// ------------------------------
3119
3120pub(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
3135// ------------------------------
3136
3137pub(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
3152// ------------------------------
3153
3154pub(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
3169// ------------------------------
3170
3171pub(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
3186// ------------------------------
3187
3188pub(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}