surrealdb_core/sql/
thing.rs

1use crate::ctx::Context;
2use crate::dbs::Options;
3use crate::doc::CursorDoc;
4use crate::err::Error;
5use crate::sql::{escape::escape_rid, id::Id, Strand, Value};
6use crate::syn;
7use derive::Store;
8use reblessive::tree::Stk;
9use revision::revisioned;
10use serde::{Deserialize, Serialize};
11use std::fmt;
12use std::str::FromStr;
13
14pub(crate) const TOKEN: &str = "$surrealdb::private::sql::Thing";
15
16#[revisioned(revision = 1)]
17#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Store, Hash)]
18#[serde(rename = "$surrealdb::private::sql::Thing")]
19#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
20#[non_exhaustive]
21pub struct Thing {
22	/// Table name
23	pub tb: String,
24	pub id: Id,
25}
26
27impl From<(&str, Id)> for Thing {
28	fn from((tb, id): (&str, Id)) -> Self {
29		Self {
30			tb: tb.to_owned(),
31			id,
32		}
33	}
34}
35
36impl From<(String, Id)> for Thing {
37	fn from((tb, id): (String, Id)) -> Self {
38		Self {
39			tb,
40			id,
41		}
42	}
43}
44
45impl From<(String, String)> for Thing {
46	fn from((tb, id): (String, String)) -> Self {
47		Self::from((tb, Id::from(id)))
48	}
49}
50
51impl From<(&str, &str)> for Thing {
52	fn from((tb, id): (&str, &str)) -> Self {
53		Self::from((tb.to_owned(), Id::from(id)))
54	}
55}
56
57impl FromStr for Thing {
58	type Err = ();
59	fn from_str(s: &str) -> Result<Self, Self::Err> {
60		Self::try_from(s)
61	}
62}
63
64impl TryFrom<String> for Thing {
65	type Error = ();
66	fn try_from(v: String) -> Result<Self, Self::Error> {
67		Self::try_from(v.as_str())
68	}
69}
70
71impl TryFrom<Strand> for Thing {
72	type Error = ();
73	fn try_from(v: Strand) -> Result<Self, Self::Error> {
74		Self::try_from(v.as_str())
75	}
76}
77
78impl TryFrom<&str> for Thing {
79	type Error = ();
80	fn try_from(v: &str) -> Result<Self, Self::Error> {
81		match syn::thing(v) {
82			Ok(v) => Ok(v),
83			_ => Err(()),
84		}
85	}
86}
87
88impl Thing {
89	/// Convert the Thing to a raw String
90	pub fn to_raw(&self) -> String {
91		self.to_string()
92	}
93}
94
95impl fmt::Display for Thing {
96	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
97		write!(f, "{}:{}", escape_rid(&self.tb), self.id)
98	}
99}
100
101impl Thing {
102	/// Process this type returning a computed simple Value
103	pub(crate) async fn compute(
104		&self,
105		stk: &mut Stk,
106		ctx: &Context<'_>,
107		opt: &Options,
108		doc: Option<&CursorDoc<'_>>,
109	) -> Result<Value, Error> {
110		Ok(Value::Thing(Thing {
111			tb: self.tb.clone(),
112			id: self.id.compute(stk, ctx, opt, doc).await?,
113		}))
114	}
115}