Skip to main content

surrealdb_types/
notification.rs

1use std::fmt::{self, Debug, Display};
2use std::str::FromStr;
3
4use serde::{Deserialize, Serialize};
5
6#[allow(unused_imports)]
7use crate as surrealdb_types;
8use crate::{SurrealValue, Uuid, Value};
9
10/// The action that caused the notification
11
12#[derive(
13	Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, SurrealValue,
14)]
15#[surreal(crate = "crate")]
16#[surreal(untagged, uppercase)]
17#[serde(rename_all = "UPPERCASE")]
18pub enum Action {
19	/// Record was created.
20	Create,
21	/// Record was updated.
22	Update,
23	/// Record was deleted.
24	Delete,
25	/// The live query was killed.
26	Killed,
27	/// The live query WHERE clause or projection raised an evaluation error.
28	///
29	/// The `result` field of the accompanying [`Notification`] carries the error
30	/// message as a string. This allows subscribers to diagnose a broken query
31	/// (e.g. a WHERE clause that always throws `InvalidFunctionArguments`) rather
32	/// than silently receiving no notifications.
33	Error,
34}
35
36impl Display for Action {
37	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
38		match *self {
39			Action::Create => write!(f, "CREATE"),
40			Action::Update => write!(f, "UPDATE"),
41			Action::Delete => write!(f, "DELETE"),
42			Action::Killed => write!(f, "KILLED"),
43			Action::Error => write!(f, "ERROR"),
44		}
45	}
46}
47
48impl FromStr for Action {
49	type Err = crate::Error;
50
51	fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
52		match s {
53			"CREATE" => Ok(Action::Create),
54			"UPDATE" => Ok(Action::Update),
55			"DELETE" => Ok(Action::Delete),
56			"KILLED" => Ok(Action::Killed),
57			"ERROR" => Ok(Action::Error),
58			_ => Err(crate::Error::validation(format!("Invalid action: {s}"), None)),
59		}
60	}
61}
62
63/// A live query notification.
64#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, SurrealValue)]
65#[surreal(crate = "crate")]
66#[non_exhaustive]
67pub struct Notification {
68	/// The id of the LIVE query to which this notification belongs
69	pub id: Uuid,
70	/// The ID of the session that sent this notification
71	pub session: Option<Uuid>,
72	/// The CREATE / UPDATE / DELETE action which caused this notification
73	pub action: Action,
74	/// The id of the document to which this notification has been made
75	pub record: Value,
76	/// The resulting notification content, usually the altered record content
77	pub result: Value,
78}
79
80impl Notification {
81	/// Construct a new notification.
82	pub fn new(
83		id: Uuid,
84		session: Option<Uuid>,
85		action: Action,
86		record: Value,
87		result: Value,
88	) -> Self {
89		Self {
90			id,
91			session,
92			action,
93			record,
94			result,
95		}
96	}
97}