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