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;
7
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, 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		// Fetch the live query key
52		let key = crate::key::node::lq::new(nid, lid);
53		// Fetch the live query key if it exists
54		match txn.get(key, None).await? {
55			Some(val) => {
56				// Decode the data for this live query
57				let val: Live = revision::from_slice(&val)?;
58				// Delete the node live query
59				let key = crate::key::node::lq::new(nid, lid);
60				txn.clr(key).await?;
61				// Delete the table live query
62				let key = crate::key::table::lq::new(&val.ns, &val.db, &val.tb, lid);
63				txn.clr(key).await?;
64				// Refresh the table cache for lives
65				if let Some(cache) = ctx.get_cache() {
66					cache.new_live_queries_version(&val.ns, &val.db, &val.tb);
67				}
68				// Clear the cache
69				txn.clear();
70			}
71			None => {
72				return Err(Error::KillStatement {
73					value: self.id.to_string(),
74				});
75			}
76		}
77		// Return the query id
78		Ok(Value::None)
79	}
80}
81
82impl fmt::Display for KillStatement {
83	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84		write!(f, "KILL {}", self.id)
85	}
86}