surrealpatch/core/src/sql/v1/thing.rs

114 lines
2.3 KiB
Rust
Raw Normal View History

use crate::ctx::Context;
use crate::dbs::{Options, Transaction};
use crate::doc::CursorDoc;
use crate::err::Error;
use crate::sql::{escape::escape_rid, id::Id, Strand, Value};
use crate::syn;
2022-04-09 09:09:01 +00:00
use derive::Store;
use revision::revisioned;
2020-06-29 15:36:01 +00:00
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
2020-06-29 15:36:01 +00:00
pub(crate) const TOKEN: &str = "$surrealdb::private::sql::Thing";
2023-04-29 15:58:22 +00:00
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[serde(rename = "$surrealdb::private::sql::Thing")]
#[revisioned(revision = 1)]
2024-01-09 15:34:52 +00:00
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
2020-06-29 15:36:01 +00:00
pub struct Thing {
/// Table name
pub tb: String,
pub id: Id,
}
impl From<(&str, Id)> for Thing {
fn from((tb, id): (&str, Id)) -> Self {
Self {
tb: tb.to_owned(),
id,
}
}
}
impl From<(String, Id)> for Thing {
fn from((tb, id): (String, Id)) -> Self {
Self {
tb,
id,
}
}
2020-06-29 15:36:01 +00:00
}
2022-03-07 18:11:44 +00:00
impl From<(String, String)> for Thing {
fn from((tb, id): (String, String)) -> Self {
Self::from((tb, Id::from(id)))
}
}
impl From<(&str, &str)> for Thing {
fn from((tb, id): (&str, &str)) -> Self {
Self::from((tb.to_owned(), Id::from(id)))
}
}
impl FromStr for Thing {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s)
}
}
impl TryFrom<String> for Thing {
type Error = ();
fn try_from(v: String) -> Result<Self, Self::Error> {
Self::try_from(v.as_str())
}
}
impl TryFrom<Strand> for Thing {
type Error = ();
fn try_from(v: Strand) -> Result<Self, Self::Error> {
Self::try_from(v.as_str())
}
}
impl TryFrom<&str> for Thing {
type Error = ();
fn try_from(v: &str) -> Result<Self, Self::Error> {
match syn::thing(v) {
Ok(v) => Ok(v),
_ => Err(()),
}
}
}
impl Thing {
2022-10-19 09:55:19 +00:00
/// Convert the Thing to a raw String
pub fn to_raw(&self) -> String {
self.to_string()
}
}
2020-06-29 15:36:01 +00:00
impl fmt::Display for Thing {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}:{}", escape_rid(&self.tb), self.id)
2021-03-29 15:43:37 +00:00
}
}
impl Thing {
/// Process this type returning a computed simple Value
pub(crate) async fn compute(
&self,
ctx: &Context<'_>,
opt: &Options,
txn: &Transaction,
doc: Option<&CursorDoc<'_>>,
) -> Result<Value, Error> {
Ok(Value::Thing(Thing {
tb: self.tb.clone(),
id: self.id.compute(ctx, opt, txn, doc).await?,
}))
}
}