surrealdb_core/sql/statements/remove/
event.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 RemoveEventStatement {
18	pub name: Ident,
19	pub what: Ident,
20	#[revision(start = 2)]
21	pub if_exists: bool,
22}
23
24impl RemoveEventStatement {
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::Event, &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			// Get the definition
35			let ev = txn.get_tb_event(ns, db, &self.what, &self.name).await?;
36			// Delete the definition
37			let key = crate::key::table::ev::new(ns, db, &ev.what, &ev.name);
38			txn.del(key).await?;
39			// Refresh the table cache for events
40			let key = crate::key::database::tb::new(ns, db, &self.what);
41			let tb = txn.get_tb(ns, db, &self.what).await?;
42			txn.set(
43				key,
44				revision::to_vec(&DefineTableStatement {
45					cache_events_ts: Uuid::now_v7(),
46					..tb.as_ref().clone()
47				})?,
48				None,
49			)
50			.await?;
51			// Clear the cache
52			if let Some(cache) = ctx.get_cache() {
53				cache.clear_tb(ns, db, &self.what);
54			}
55			// Clear the cache
56			txn.clear();
57			// Ok all good
58			Ok(Value::None)
59		}
60		.await;
61		match future {
62			Err(Error::EvNotFound {
63				..
64			}) if self.if_exists => Ok(Value::None),
65			v => v,
66		}
67	}
68}
69
70impl Display for RemoveEventStatement {
71	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
72		write!(f, "REMOVE EVENT")?;
73		if self.if_exists {
74			write!(f, " IF EXISTS")?
75		}
76		write!(f, " {} ON {}", self.name, self.what)?;
77		Ok(())
78	}
79}