surrealdb_core/sql/statements/remove/
index.rs

1use crate::ctx::Context;
2use crate::dbs::Options;
3use crate::err::Error;
4use crate::iam::{Action, ResourceKind};
5use crate::sql::statements::define::DefineTableStatement;
6use crate::sql::{Base, Ident, Value};
7
8use revision::revisioned;
9use serde::{Deserialize, Serialize};
10use std::fmt::{self, Display, Formatter};
11use uuid::Uuid;
12
13#[revisioned(revision = 2)]
14#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Hash)]
15#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
16#[non_exhaustive]
17pub struct RemoveIndexStatement {
18	pub name: Ident,
19	pub what: Ident,
20	#[revision(start = 2)]
21	pub if_exists: bool,
22}
23
24impl RemoveIndexStatement {
25	/// Process this type returning a computed simple Value
26	pub(crate) async fn compute(&self, ctx: &Context, opt: &Options) -> Result<Value, Error> {
27		let future = async {
28			// Allowed to run?
29			opt.is_allowed(Action::Edit, ResourceKind::Index, &Base::Db)?;
30			// Get the NS and DB
31			let (ns, db) = opt.ns_db()?;
32			// Get the transaction
33			let txn = ctx.tx();
34			// Clear the index store cache
35			ctx.get_index_stores()
36				.index_removed(ctx.get_index_builder(), &txn, ns, db, &self.what, &self.name)
37				.await?;
38			// Delete the definition
39			let key = crate::key::table::ix::new(ns, db, &self.what, &self.name);
40			txn.del(key).await?;
41			// Remove the index data
42			let key = crate::key::index::all::new(ns, db, &self.what, &self.name);
43			txn.delp(key).await?;
44			// Refresh the table cache for indexes
45			let key = crate::key::database::tb::new(ns, db, &self.what);
46			let tb = txn.get_tb(ns, db, &self.what).await?;
47			txn.set(
48				key,
49				revision::to_vec(&DefineTableStatement {
50					cache_indexes_ts: Uuid::now_v7(),
51					..tb.as_ref().clone()
52				})?,
53				None,
54			)
55			.await?;
56			// Clear the cache
57			if let Some(cache) = ctx.get_cache() {
58				cache.clear_tb(ns, db, &self.what);
59			}
60			// Clear the cache
61			txn.clear();
62			// Ok all good
63			Ok(Value::None)
64		}
65		.await;
66		match future {
67			Err(Error::IxNotFound {
68				..
69			}) if self.if_exists => Ok(Value::None),
70			v => v,
71		}
72	}
73}
74
75impl Display for RemoveIndexStatement {
76	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
77		write!(f, "REMOVE INDEX")?;
78		if self.if_exists {
79			write!(f, " IF EXISTS")?
80		}
81		write!(f, " {} ON {}", self.name, self.what)?;
82		Ok(())
83	}
84}