surrealdb_sql/statements/define/
token.rs

1use crate::ctx::Context;
2use crate::dbs::{Options, Transaction};
3use crate::doc::CursorDoc;
4use crate::err::Error;
5use crate::iam::{Action, ResourceKind};
6use crate::{escape::quote_str, Algorithm, Base, Ident, Strand, Value};
7use derive::Store;
8use revision::revisioned;
9use serde::{Deserialize, Serialize};
10use std::fmt::{self, Display};
11
12#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
13#[revisioned(revision = 1)]
14pub struct DefineTokenStatement {
15	pub name: Ident,
16	pub base: Base,
17	pub kind: Algorithm,
18	pub code: String,
19	pub comment: Option<Strand>,
20}
21
22impl DefineTokenStatement {
23	/// Process this type returning a computed simple Value
24	pub(crate) async fn compute(
25		&self,
26		_ctx: &Context<'_>,
27		opt: &Options,
28		txn: &Transaction,
29		_doc: Option<&CursorDoc<'_>>,
30	) -> Result<Value, Error> {
31		opt.is_allowed(Action::Edit, ResourceKind::Actor, &self.base)?;
32
33		match &self.base {
34			Base::Ns => {
35				// Claim transaction
36				let mut run = txn.lock().await;
37				// Clear the cache
38				run.clear_cache();
39				// Process the statement
40				let key = crate::key::namespace::tk::new(opt.ns(), &self.name);
41				run.add_ns(opt.ns(), opt.strict).await?;
42				run.set(key, self).await?;
43				// Ok all good
44				Ok(Value::None)
45			}
46			Base::Db => {
47				// Claim transaction
48				let mut run = txn.lock().await;
49				// Clear the cache
50				run.clear_cache();
51				// Process the statement
52				let key = crate::key::database::tk::new(opt.ns(), opt.db(), &self.name);
53				run.add_ns(opt.ns(), opt.strict).await?;
54				run.add_db(opt.ns(), opt.db(), opt.strict).await?;
55				run.set(key, self).await?;
56				// Ok all good
57				Ok(Value::None)
58			}
59			Base::Sc(sc) => {
60				// Claim transaction
61				let mut run = txn.lock().await;
62				// Clear the cache
63				run.clear_cache();
64				// Process the statement
65				let key = crate::key::scope::tk::new(opt.ns(), opt.db(), sc, &self.name);
66				run.add_ns(opt.ns(), opt.strict).await?;
67				run.add_db(opt.ns(), opt.db(), opt.strict).await?;
68				run.add_sc(opt.ns(), opt.db(), sc, opt.strict).await?;
69				run.set(key, self).await?;
70				// Ok all good
71				Ok(Value::None)
72			}
73			// Other levels are not supported
74			_ => Err(Error::InvalidLevel(self.base.to_string())),
75		}
76	}
77}
78
79impl Display for DefineTokenStatement {
80	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81		write!(
82			f,
83			"DEFINE TOKEN {} ON {} TYPE {} VALUE {}",
84			self.name,
85			self.base,
86			self.kind,
87			quote_str(&self.code)
88		)?;
89		if let Some(ref v) = self.comment {
90			write!(f, " COMMENT {v}")?
91		}
92		Ok(())
93	}
94}