surrealdb_sql/statements/
kill.rs

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