surrealdb_core/sql/statements/
kill.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use std::fmt;

use derive::Store;
use reblessive::tree::Stk;
use revision::revisioned;
use serde::{Deserialize, Serialize};

use crate::ctx::Context;
use crate::dbs::Options;
use crate::doc::CursorDoc;
use crate::err::Error;
use crate::fflags::FFLAGS;
use crate::kvs::lq_structs::{KillEntry, TrackedResult};
use crate::sql::Uuid;
use crate::sql::Value;

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct KillStatement {
	// Uuid of Live Query
	// or Param resolving to Uuid of Live Query
	pub id: Value,
}

impl KillStatement {
	/// Process this type returning a computed simple Value
	pub(crate) async fn compute(
		&self,
		stk: &mut Stk,
		ctx: &Context<'_>,
		opt: &Options,
		_doc: Option<&CursorDoc<'_>>,
	) -> Result<Value, Error> {
		// Is realtime enabled?
		opt.realtime()?;
		// Valid options?
		opt.valid_for_db()?;
		// Resolve live query id
		let live_query_id = match &self.id {
			Value::Uuid(id) => *id,
			Value::Param(param) => match param.compute(stk, ctx, opt, None).await? {
				Value::Uuid(id) => id,
				Value::Strand(id) => match uuid::Uuid::try_parse(&id) {
					Ok(id) => Uuid(id),
					_ => {
						return Err(Error::KillStatement {
							value:
								"KILL received a parameter that could not be converted to a UUID"
									.to_string(),
						});
					}
				},
				_ => {
					return Err(Error::KillStatement {
						value: "KILL received a parameter that was not expected".to_string(),
					});
				}
			},
			Value::Strand(maybe_id) => match uuid::Uuid::try_parse(maybe_id) {
				Ok(id) => Uuid(id),
				_ => {
					return Err(Error::KillStatement {
						value: "KILL received a Strand that could not be converted to a UUID"
							.to_string(),
					});
				}
			},
			_ => {
				return Err(Error::KillStatement {
					value: "Unhandled type for KILL statement".to_string(),
				});
			}
		};
		// Claim transaction
		let mut run = ctx.tx_lock().await;
		if FFLAGS.change_feed_live_queries.enabled() {
			run.pre_commit_register_async_event(TrackedResult::KillQuery(KillEntry {
				live_id: live_query_id,
				ns: opt.ns()?.to_string(),
				db: opt.db()?.to_string(),
			}))?;
		} else {
			// Fetch the live query key
			let key = crate::key::node::lq::new(opt.id()?, live_query_id.0, opt.ns()?, opt.db()?);
			// Fetch the live query key if it exists
			match run.get(key).await? {
				Some(val) => match std::str::from_utf8(&val) {
					Ok(tb) => {
						// Delete the node live query
						let key = crate::key::node::lq::new(
							opt.id()?,
							live_query_id.0,
							opt.ns()?,
							opt.db()?,
						);
						run.del(key).await?;
						// Delete the table live query
						let key =
							crate::key::table::lq::new(opt.ns()?, opt.db()?, tb, live_query_id.0);
						run.del(key).await?;
					}
					_ => {
						return Err(Error::KillStatement {
							value: self.id.to_string(),
						});
					}
				},
				None => {
					return Err(Error::KillStatement {
						value: "KILL statement uuid did not exist".to_string(),
					});
				}
			}
		}
		// Return the query id
		Ok(Value::None)
	}
}

impl fmt::Display for KillStatement {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		write!(f, "KILL {}", self.id)
	}
}

#[cfg(test)]
mod test {
	use std::str::FromStr;

	use crate::ctx::Context;
	use crate::dbs::Options;
	use crate::fflags::FFLAGS;
	use crate::kvs::lq_structs::{KillEntry, TrackedResult};
	use crate::kvs::{Datastore, LockType, TransactionType};
	use crate::sql::statements::KillStatement;
	use crate::sql::uuid::Uuid;

	#[test_log::test(tokio::test)]
	async fn kill_handles_uuid_event_registration() {
		if !FFLAGS.change_feed_live_queries.enabled() {
			return;
		}
		let res = KillStatement {
			id: Uuid::from_str("8f92f057-c739-4bf2-9d0c-a74d01299efc").unwrap().into(),
		};
		let ctx = Context::default();
		let opt = Options::new()
			.with_id(uuid::Uuid::from_str("8c41d9f7-a627-40f7-86f5-59d56cd765c6").unwrap())
			.with_live(true)
			.with_db(Some("database".into()))
			.with_ns(Some("namespace".into()));
		let ds = Datastore::new("memory").await.unwrap();
		let tx =
			ds.transaction(TransactionType::Write, LockType::Optimistic).await.unwrap().enclose();
		let ctx = ctx.set_transaction(tx.clone());

		let mut stack = reblessive::tree::TreeStack::new();

		stack.enter(|stk| res.compute(stk, &ctx, &opt, None)).finish().await.unwrap();

		let mut tx = tx.lock().await;
		tx.commit().await.unwrap();

		// Validate sent
		assert_eq!(
			tx.consume_pending_live_queries(),
			vec![TrackedResult::KillQuery(KillEntry {
				live_id: Uuid::from_str("8f92f057-c739-4bf2-9d0c-a74d01299efc").unwrap(),
				ns: "namespace".to_string(),
				db: "database".to_string(),
			})]
		);
	}
}