surrealdb_sql/statements/define/
scope.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::{Base, Duration, Ident, Strand, Value};
7use derive::Store;
8use rand::distributions::Alphanumeric;
9use rand::Rng;
10use revision::revisioned;
11use serde::{Deserialize, Serialize};
12use std::fmt::{self, Display};
13
14#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
15#[revisioned(revision = 1)]
16pub struct DefineScopeStatement {
17	pub name: Ident,
18	pub code: String,
19	pub session: Option<Duration>,
20	pub signup: Option<Value>,
21	pub signin: Option<Value>,
22	pub comment: Option<Strand>,
23}
24
25impl DefineScopeStatement {
26	/// Process this type returning a computed simple Value
27	pub(crate) async fn compute(
28		&self,
29		_ctx: &Context<'_>,
30		opt: &Options,
31		txn: &Transaction,
32		_doc: Option<&CursorDoc<'_>>,
33	) -> Result<Value, Error> {
34		// Allowed to run?
35		opt.is_allowed(Action::Edit, ResourceKind::Scope, &Base::Db)?;
36		// Claim transaction
37		let mut run = txn.lock().await;
38		// Clear the cache
39		run.clear_cache();
40		// Process the statement
41		let key = crate::key::database::sc::new(opt.ns(), opt.db(), &self.name);
42		run.add_ns(opt.ns(), opt.strict).await?;
43		run.add_db(opt.ns(), opt.db(), opt.strict).await?;
44		run.set(key, self).await?;
45		// Ok all good
46		Ok(Value::None)
47	}
48
49	pub fn random_code() -> String {
50		rand::thread_rng().sample_iter(&Alphanumeric).take(128).map(char::from).collect::<String>()
51	}
52}
53
54impl Display for DefineScopeStatement {
55	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56		write!(f, "DEFINE SCOPE {}", self.name)?;
57		if let Some(ref v) = self.session {
58			write!(f, " SESSION {v}")?
59		}
60		if let Some(ref v) = self.signup {
61			write!(f, " SIGNUP {v}")?
62		}
63		if let Some(ref v) = self.signin {
64			write!(f, " SIGNIN {v}")?
65		}
66		if let Some(ref v) = self.comment {
67			write!(f, " COMMENT {v}")?
68		}
69		Ok(())
70	}
71}