surrealdb_core/sql/
cast.rs

1use crate::ctx::Context;
2use crate::dbs::Options;
3use crate::doc::CursorDoc;
4use crate::err::Error;
5use crate::sql::{Idiom, Kind, Value};
6use reblessive::tree::Stk;
7use revision::revisioned;
8use serde::{Deserialize, Serialize};
9use std::cmp::Ordering;
10use std::fmt;
11
12pub(crate) const TOKEN: &str = "$surrealdb::private::sql::Cast";
13
14#[revisioned(revision = 1)]
15#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
16#[serde(rename = "$surrealdb::private::sql::Cast")]
17#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
18#[non_exhaustive]
19pub struct Cast(pub Kind, pub Value);
20
21impl PartialOrd for Cast {
22	#[inline]
23	fn partial_cmp(&self, _: &Self) -> Option<Ordering> {
24		None
25	}
26}
27
28impl Cast {
29	/// Convert cast to a field name
30	pub fn to_idiom(&self) -> Idiom {
31		self.1.to_idiom()
32	}
33}
34
35impl Cast {
36	/// Check if we require a writeable transaction
37	pub(crate) fn writeable(&self) -> bool {
38		self.1.writeable()
39	}
40	/// Checks whether all array values are static values
41	pub(crate) fn is_static(&self) -> bool {
42		self.1.is_static()
43	}
44	/// Was marked recursively
45	pub(crate) async fn compute(
46		&self,
47		stk: &mut Stk,
48		ctx: &Context,
49		opt: &Options,
50		doc: Option<&CursorDoc>,
51	) -> Result<Value, Error> {
52		// Compute the value to be cast and convert it
53		stk.run(|stk| self.1.compute(stk, ctx, opt, doc)).await?.convert_to(&self.0)
54	}
55}
56
57impl fmt::Display for Cast {
58	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59		write!(f, "<{}> {}", self.0, self.1)
60	}
61}