surrealdb_sql/statements/define/
namespace.rs1use crate::ctx::Context;
2use crate::dbs::{Options, Transaction};
3use crate::doc::CursorDoc;
4use crate::err::Error;
5use crate::iam::{Action, ResourceKind};
6use crate::{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 DefineNamespaceStatement {
15 pub id: Option<u32>,
16 pub name: Ident,
17 pub comment: Option<Strand>,
18}
19
20impl DefineNamespaceStatement {
21 pub(crate) async fn compute(
23 &self,
24 _ctx: &Context<'_>,
25 opt: &Options,
26 txn: &Transaction,
27 _doc: Option<&CursorDoc<'_>>,
28 ) -> Result<Value, Error> {
29 opt.is_allowed(Action::Edit, ResourceKind::Namespace, &Base::Root)?;
31 let key = crate::key::root::ns::new(&self.name);
33 let mut run = txn.lock().await;
35 run.clear_cache();
37 if self.id.is_none() {
39 let mut ns = self.clone();
40 ns.id = Some(run.get_next_ns_id().await?);
41 run.set(key, ns).await?;
42 } else {
43 run.set(key, self).await?;
44 }
45 Ok(Value::None)
47 }
48}
49
50impl Display for DefineNamespaceStatement {
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52 write!(f, "DEFINE NAMESPACE {}", self.name)?;
53 if let Some(ref v) = self.comment {
54 write!(f, " COMMENT {v}")?
55 }
56 Ok(())
57 }
58}