surrealdb_core/cf/
mutations.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
use crate::sql::array::Array;
use crate::sql::object::Object;
use crate::sql::statements::DefineTableStatement;
use crate::sql::thing::Thing;
use crate::sql::value::Value;
use crate::vs::to_u128_be;
use derive::Store;
use revision::revisioned;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::fmt::{self, Display, Formatter};

// Mutation is a single mutation to a table.
#[revisioned(revision = 2)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
pub enum TableMutation {
	// Although the Value is supposed to contain a field "id" of Thing,
	// we do include it in the first field for convenience.
	Set(Thing, Value),
	Del(Thing),
	Def(DefineTableStatement),
	#[revision(start = 2)]
	// Includes the previous value that may be None
	SetPrevious(Thing, Value, Value),
}

impl From<DefineTableStatement> for Value {
	#[inline]
	fn from(v: DefineTableStatement) -> Self {
		let mut h = HashMap::<&str, Value>::new();
		if let Some(id) = v.id {
			h.insert("id", id.into());
		}
		h.insert("name", v.name.0.into());
		Value::Object(Object::from(h))
	}
}

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
pub struct TableMutations(pub String, pub Vec<TableMutation>);

impl TableMutations {
	pub fn new(tb: String) -> Self {
		Self(tb, Vec::new())
	}
}

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
pub struct DatabaseMutation(pub Vec<TableMutations>);

impl DatabaseMutation {
	pub fn new() -> Self {
		Self(Vec::new())
	}
}

impl Default for DatabaseMutation {
	fn default() -> Self {
		Self::new()
	}
}
// Change is a set of mutations made to a table at the specific timestamp.
#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
pub struct ChangeSet(pub [u8; 10], pub DatabaseMutation);

impl TableMutation {
	pub fn into_value(self) -> Value {
		let (k, v) = match self {
			TableMutation::Set(_t, v) => ("update".to_string(), v),
			TableMutation::SetPrevious(_t, Value::None, v) => ("create".to_string(), v),
			TableMutation::SetPrevious(_t, _previous, v) => ("update".to_string(), v),
			TableMutation::Del(t) => {
				// TODO(phughk): Future PR for lq on cf feature, store update in delete for diff and notification
				let mut h = BTreeMap::<String, Value>::new();
				h.insert("id".to_string(), Value::Thing(t));
				let o = Object::from(h);
				("delete".to_string(), Value::Object(o))
			}
			TableMutation::Def(t) => ("define_table".to_string(), Value::from(t)),
		};

		let mut h = BTreeMap::<String, Value>::new();
		h.insert(k, v);
		let o = crate::sql::object::Object::from(h);
		Value::Object(o)
	}
}

impl DatabaseMutation {
	pub fn into_value(self) -> Value {
		let mut changes = Vec::<Value>::new();
		for tbs in self.0 {
			for tb in tbs.1 {
				changes.push(tb.into_value());
			}
		}
		Value::Array(Array::from(changes))
	}
}

impl ChangeSet {
	pub fn into_value(self) -> Value {
		let mut m = BTreeMap::<String, Value>::new();
		let vs = to_u128_be(self.0);
		m.insert("versionstamp".to_string(), Value::from(vs));
		m.insert("changes".to_string(), self.1.into_value());
		let so: Object = m.into();
		Value::Object(so)
	}
}

impl Display for TableMutation {
	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
		match self {
			TableMutation::Set(id, v) => write!(f, "SET {} {}", id, v),
			TableMutation::SetPrevious(id, _previous, v) => write!(f, "SET {} {}", id, v),
			TableMutation::Del(id) => write!(f, "DEL {}", id),
			TableMutation::Def(t) => write!(f, "{}", t),
		}
	}
}

impl Display for TableMutations {
	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
		let tb = &self.0;
		let muts = &self.1;
		write!(f, "{}", tb)?;
		muts.iter().try_for_each(|v| write!(f, "{}", v))
	}
}

impl Display for DatabaseMutation {
	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
		let x = &self.0;

		x.iter().try_for_each(|v| write!(f, "{}", v))
	}
}

impl Display for ChangeSet {
	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
		let x = &self.1;

		write!(f, "{}", x)
	}
}

// WriteMutationSet is a set of mutations to be to a table at the specific timestamp.
#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
pub struct WriteMutationSet(pub Vec<TableMutations>);

impl WriteMutationSet {
	pub fn new() -> Self {
		Self(Vec::new())
	}
}

impl Default for WriteMutationSet {
	fn default() -> Self {
		Self::new()
	}
}

#[cfg(test)]
mod tests {
	use crate::sql::Strand;

	#[test]
	fn serialization() {
		use super::*;
		use std::collections::HashMap;
		let cs = ChangeSet(
			[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
			DatabaseMutation(vec![TableMutations(
				"mytb".to_string(),
				vec![
					TableMutation::Set(
						Thing::from(("mytb".to_string(), "tobie".to_string())),
						Value::Object(Object::from(HashMap::from([
							(
								"id",
								Value::from(Thing::from(("mytb".to_string(), "tobie".to_string()))),
							),
							("note", Value::from("surreal")),
						]))),
					),
					TableMutation::Del(Thing::from(("mytb".to_string(), "tobie".to_string()))),
					TableMutation::Def(DefineTableStatement {
						name: "mytb".into(),
						..DefineTableStatement::default()
					}),
				],
			)]),
		);
		let v = cs.into_value().into_json();
		let s = serde_json::to_string(&v).unwrap();
		assert_eq!(
			s,
			r#"{"changes":[{"update":{"id":"mytb:tobie","note":"surreal"}},{"delete":{"id":"mytb:tobie"}},{"define_table":{"name":"mytb"}}],"versionstamp":1}"#
		);
	}

	#[test]
	fn serialization_rev2() {
		use super::*;
		use std::collections::HashMap;
		let cs = ChangeSet(
			[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
			DatabaseMutation(vec![TableMutations(
				"mytb".to_string(),
				vec![
					TableMutation::SetPrevious(
						Thing::from(("mytb".to_string(), "tobie".to_string())),
						Value::None,
						Value::Object(Object::from(HashMap::from([
							(
								"id",
								Value::from(Thing::from(("mytb".to_string(), "tobie".to_string()))),
							),
							("note", Value::from("surreal")),
						]))),
					),
					TableMutation::SetPrevious(
						Thing::from(("mytb".to_string(), "tobie".to_string())),
						Value::Strand(Strand::from("this would normally be an object")),
						Value::Object(Object::from(HashMap::from([
							(
								"id",
								Value::from(Thing::from((
									"mytb".to_string(),
									"tobie2".to_string(),
								))),
							),
							("note", Value::from("surreal")),
						]))),
					),
					TableMutation::Del(Thing::from(("mytb".to_string(), "tobie".to_string()))),
					TableMutation::Def(DefineTableStatement {
						name: "mytb".into(),
						..DefineTableStatement::default()
					}),
				],
			)]),
		);
		let v = cs.into_value().into_json();
		let s = serde_json::to_string(&v).unwrap();
		assert_eq!(
			s,
			r#"{"changes":[{"create":{"id":"mytb:tobie","note":"surreal"}},{"update":{"id":"mytb:tobie2","note":"surreal"}},{"delete":{"id":"mytb:tobie"}},{"define_table":{"name":"mytb"}}],"versionstamp":1}"#
		);
	}
}