surrealdb/sql/value/
value.rs

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