surrealdb_core/sql/statements/remove/
analyzer.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 = 2)]
12#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Hash)]
13#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
14#[non_exhaustive]
15pub struct RemoveAnalyzerStatement {
16	pub name: Ident,
17	#[revision(start = 2)]
18	pub if_exists: bool,
19}
20
21impl RemoveAnalyzerStatement {
22	pub(crate) async fn compute(&self, ctx: &Context, opt: &Options) -> Result<Value, Error> {
23		let future = async {
24			let (ns, db) = opt.ns_db()?;
25			// Allowed to run?
26			opt.is_allowed(Action::Edit, ResourceKind::Analyzer, &Base::Db)?;
27			// Get the transaction
28			let txn = ctx.tx();
29			// Get the definition
30			let az = txn.get_db_analyzer(ns, db, &self.name).await?;
31			// Delete the definition
32			let key = crate::key::database::az::new(ns, db, &az.name);
33			txn.del(key).await?;
34			// Clear the cache
35			txn.clear();
36			// Cleanup in-memory mappers if not used anymore
37			let azs = txn.all_db_analyzers(ns, db).await?;
38			ctx.get_index_stores().mappers().cleanup(&azs);
39			// TODO Check that the analyzer is not used in any schema
40			// Ok all good
41			Ok(Value::None)
42		}
43		.await;
44		match future {
45			Err(Error::AzNotFound {
46				..
47			}) if self.if_exists => Ok(Value::None),
48			v => v,
49		}
50	}
51}
52
53impl Display for RemoveAnalyzerStatement {
54	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
55		write!(f, "REMOVE ANALYZER")?;
56		if self.if_exists {
57			write!(f, " IF EXISTS")?
58		}
59		write!(f, " {}", self.name)?;
60		Ok(())
61	}
62}