surrealdb_core/sql/statements/
kill.rs

1use crate::ctx::Context;
2use crate::dbs::Options;
3use crate::doc::CursorDoc;
4use crate::err::Error;
5use crate::kvs::Live;
6use crate::sql::Value;
7use derive::Store;
8use reblessive::tree::Stk;
9use revision::revisioned;
10use serde::{Deserialize, Serialize};
11use std::fmt;
12
13#[revisioned(revision = 1)]
14#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
15#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
16#[non_exhaustive]
17pub struct KillStatement {
18	// Uuid of Live Query
19	// or Param resolving to Uuid of Live Query
20	pub id: Value,
21}
22
23impl KillStatement {
24	/// Process this type returning a computed simple Value
25	pub(crate) async fn compute(
26		&self,
27		stk: &mut Stk,
28		ctx: &Context<'_>,
29		opt: &Options,
30		_doc: Option<&CursorDoc<'_>>,
31	) -> Result<Value, Error> {
32		// Is realtime enabled?
33		opt.realtime()?;
34		// Valid options?
35		opt.valid_for_db()?;
36		// Resolve live query id
37		let lid = match self.id.compute(stk, ctx, opt, None).await?.convert_to_uuid() {
38			Err(_) => {
39				return Err(Error::KillStatement {
40					value: self.id.to_string(),
41				})
42			}
43			Ok(id) => id,
44		};
45		// Get the Node ID
46		let nid = opt.id()?;
47		// Get the LIVE ID
48		let lid = lid.0;
49		// Get the transaction
50		let txn = ctx.tx();
51		// Lock the transaction
52		let mut txn = txn.lock().await;
53		// Fetch the live query key
54		let key = crate::key::node::lq::new(nid, lid);
55		// Fetch the live query key if it exists
56		match txn.get(key).await? {
57			Some(val) => {
58				// Decode the data for this live query
59				let val: Live = val.into();
60				// Delete the node live query
61				let key = crate::key::node::lq::new(nid, lid);
62				txn.del(key).await?;
63				// Delete the table live query
64				let key = crate::key::table::lq::new(&val.ns, &val.db, &val.tb, lid);
65				txn.del(key).await?;
66			}
67			None => {
68				return Err(Error::KillStatement {
69					value: self.id.to_string(),
70				});
71			}
72		}
73		// Return the query id
74		Ok(Value::None)
75	}
76}
77
78impl fmt::Display for KillStatement {
79	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
80		write!(f, "KILL {}", self.id)
81	}
82}