surrealdb_core/sql/statements/remove/
model.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};
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 RemoveModelStatement {
16	pub name: Ident,
17	pub version: String,
18	#[revision(start = 2)]
19	pub if_exists: bool,
20}
21
22impl RemoveModelStatement {
23	/// Process this type returning a computed simple Value
24	pub(crate) async fn compute(&self, ctx: &Context, opt: &Options) -> Result<Value, Error> {
25		let future = async {
26			// Allowed to run?
27			opt.is_allowed(Action::Edit, ResourceKind::Model, &Base::Db)?;
28			// Get the transaction
29			let txn = ctx.tx();
30			// Get the defined model
31			let (ns, db) = opt.ns_db()?;
32			let ml = txn.get_db_model(ns, db, &self.name, &self.version).await?;
33			// Delete the definition
34			let key = crate::key::database::ml::new(ns, db, &ml.name, &ml.version);
35			txn.del(key).await?;
36			// Clear the cache
37			txn.clear();
38			// TODO Remove the model file from storage
39			// Ok all good
40			Ok(Value::None)
41		}
42		.await;
43		match future {
44			Err(Error::MlNotFound {
45				..
46			}) if self.if_exists => Ok(Value::None),
47			v => v,
48		}
49	}
50}
51
52impl Display for RemoveModelStatement {
53	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54		// Bypass ident display since we don't want backticks arround the ident.
55		write!(f, "REMOVE MODEL")?;
56		if self.if_exists {
57			write!(f, " IF EXISTS")?
58		}
59		write!(f, " ml::{}<{}>", self.name.0, self.version)?;
60		Ok(())
61	}
62}