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