surrealdb_core/sql/statements/remove/
namespace.rs

1use crate::ctx::Context;
2use crate::dbs::Options;
3use crate::err::Error;
4use crate::iam::{Action, ResourceKind};
5use crate::sql::{Base, Ident, Value};
6
7use revision::revisioned;
8use serde::{Deserialize, Serialize};
9use std::fmt::{self, Display, Formatter};
10
11#[revisioned(revision = 3)]
12#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Hash)]
13#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
14#[non_exhaustive]
15pub struct RemoveNamespaceStatement {
16	pub name: Ident,
17	#[revision(start = 2)]
18	pub if_exists: bool,
19	#[revision(start = 3)]
20	pub expunge: bool,
21}
22
23impl RemoveNamespaceStatement {
24	/// Process this type returning a computed simple Value
25	pub(crate) async fn compute(&self, ctx: &Context, opt: &Options) -> Result<Value, Error> {
26		let future = async {
27			// Allowed to run?
28			opt.is_allowed(Action::Edit, ResourceKind::Namespace, &Base::Root)?;
29			// Get the transaction
30			let txn = ctx.tx();
31			// Remove the index stores
32			ctx.get_index_stores()
33				.namespace_removed(ctx.get_index_builder(), &txn, &self.name)
34				.await?;
35			// Get the definition
36			let ns = txn.get_ns(&self.name).await?;
37			// Delete the definition
38			let key = crate::key::root::ns::new(&ns.name);
39			match self.expunge {
40				true => txn.clr(key).await?,
41				false => txn.del(key).await?,
42			};
43			// Delete the resource data
44			let key = crate::key::namespace::all::new(&ns.name);
45			match self.expunge {
46				true => txn.clrp(key).await?,
47				false => txn.delp(key).await?,
48			};
49			// Clear the cache
50			if let Some(cache) = ctx.get_cache() {
51				cache.clear();
52			}
53			// Clear the cache
54			txn.clear();
55			// Ok all good
56			Ok(Value::None)
57		}
58		.await;
59		match future {
60			Err(Error::NsNotFound {
61				..
62			}) if self.if_exists => Ok(Value::None),
63			v => v,
64		}
65	}
66}
67
68impl Display for RemoveNamespaceStatement {
69	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
70		write!(f, "REMOVE NAMESPACE")?;
71		if self.if_exists {
72			write!(f, " IF EXISTS")?
73		}
74		write!(f, " {}", self.name)?;
75		Ok(())
76	}
77}