surrealdb-core 3.2.3

A scalable, distributed, collaborative, document-graph database, for the realtime web
Documentation
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use anyhow::{Result, bail, ensure};
use surrealdb_types::ToSql;

use crate::err::Error;
use crate::expr::Operation;
use crate::expr::operation::PatchError;
use crate::expr::part::Part;
use crate::val::{Strand, Value};

impl Value {
	pub(crate) fn patch(&mut self, ops: Value) -> Result<()> {
		let mut this = self.clone();
		// Create a new object for testing and patching
		// Loop over the patch operations and apply them
		for operation in Operation::value_to_operations(ops)
			.map_err(Error::InvalidPatch)
			.map_err(anyhow::Error::new)?
		{
			let to_parts = |path: Vec<Strand>| {
				path.into_iter()
					.map(|p| {
						if let Ok(i) = p.as_str().parse::<i64>() {
							Part::index_int(i)
						} else {
							Part::Field(p)
						}
					})
					.collect::<Vec<_>>()
			};

			match operation {
				// Add a value
				Operation::Add {
					path,
					value,
				} => {
					// Split the last path part from the path
					if let Some((last, left)) = path.split_last() {
						if let Ok(x) = last.as_str().parse::<usize>() {
							let path =
								left.iter().map(|x| Part::Field(x.clone())).collect::<Vec<_>>();

							match this.pick(&path) {
								Value::Array(mut v) => {
									// RFC 6902 ยง4.1: the index for `add` MUST NOT
									// be greater than the number of elements in
									// the array. `insert(len, _)` is the spec's
									// append form; anything beyond is rejected.
									if x > v.len() {
										bail!(Error::InvalidPatch(PatchError {
											message: format!(
												"index {x} is out of bounds for array of length {len}",
												len = v.len(),
											),
										}));
									}
									v.insert(x, value);
									this.put(&path, Value::Array(v));
								}
								_ => this.put(&path, value),
							}
							continue;
						}

						if last.as_str() == "-" {
							let path =
								left.iter().map(|x| Part::Field(x.clone())).collect::<Vec<_>>();

							match this.pick(&path) {
								Value::Array(mut v) => {
									v.push(value);
									this.put(&path, Value::Array(v));
								}
								_ => this.put(&path, value),
							}
							continue;
						}
					}

					let path = path.into_iter().map(Part::Field).collect::<Vec<_>>();
					match this.pick(&path) {
						Value::Array(_) => this.inc(&path, value)?,
						_ => this.put(&path, value),
					}
				}
				// Remove a value at the specified path
				Operation::Remove {
					path,
				} => {
					let path = to_parts(path);
					this.cut(&path);
				}
				// Replace a value at the specified path
				Operation::Replace {
					path,
					value,
				} => {
					let path = path.into_iter().map(Part::Field).collect::<Vec<_>>();
					this.put(&path, value)
				}
				// Modify a string at the specified path
				Operation::Change {
					path,
					value,
				} => {
					let path = path.into_iter().map(Part::Field).collect::<Vec<_>>();
					if let Value::String(p) = value
						&& let Value::String(v) = this.pick(&path)
					{
						let dmp = dmp::new();
						let pch = dmp.patch_from_text(p.into_string()).map_err(|e| {
							Error::InvalidPatch(PatchError {
								message: format!("{e:?}"),
							})
						})?;
						let (txt, _) = dmp.patch_apply(&pch, v.as_str()).map_err(|e| {
							Error::InvalidPatch(PatchError {
								message: format!("{e:?}"),
							})
						})?;
						let txt = txt.into_iter().collect::<String>();
						this.put(&path, Value::from(txt));
					}
				}
				// Copy a value from one field to another
				Operation::Copy {
					path,
					from,
				} => {
					let from = from.into_iter().map(Part::Field).collect::<Vec<_>>();
					let path = path.into_iter().map(Part::Field).collect::<Vec<_>>();

					let val = this.pick(&from);
					this.put(&path, val);
				}
				// Move a value from one field to another
				Operation::Move {
					path,
					from,
				} => {
					let from = from.into_iter().map(Part::Field).collect::<Vec<_>>();
					let path = path.into_iter().map(Part::Field).collect::<Vec<_>>();

					let val = this.pick(&from);
					this.put(&path, val);
					this.cut(&from);
				}
				// Test whether a value matches another value
				Operation::Test {
					path,
					value,
				} => {
					let path = path.into_iter().map(Part::Field).collect::<Vec<_>>();
					let val = this.pick(&path);
					ensure!(
						value == val,
						Error::PatchTest {
							expected: value.to_sql(),
							got: val.to_sql(),
						}
					);
				}
			}
		}
		*self = this;
		// Everything ok
		Ok(())
	}
}

#[cfg(test)]
mod tests {
	use crate::expr::Operation;
	use crate::syn;

	macro_rules! parse_val {
		($input:expr) => {
			crate::val::convert_public_value_to_internal(syn::value($input).unwrap())
		};
	}

	#[tokio::test]
	async fn patch_add_simple() {
		let mut val = parse_val!("{ test: { other: null, something: 123 } }");
		let ops = parse_val!("[{ op: 'add', path: '/temp', value: true }]");
		let res = parse_val!("{ test: { other: null, something: 123 }, temp: true }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_remove_simple() {
		let mut val = parse_val!("{ test: { other: null, something: 123 }, temp: true }");
		let ops = parse_val!("[{ op: 'remove', path: '/temp' }]");
		let res = parse_val!("{ test: { other: null, something: 123 } }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_replace_simple() {
		let mut val = parse_val!("{ test: { other: null, something: 123 }, temp: true }");
		let ops = parse_val!("[{ op: 'replace', path: '/temp', value: 'text' }]");
		let res = parse_val!("{ test: { other: null, something: 123 }, temp: 'text' }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_change_simple() {
		let mut val = parse_val!("{ test: { other: null, something: 123 }, temp: 'test' }");
		let ops = parse_val!(
			"[{ op: 'change', path: '/temp', value: '@@ -1,4 +1,4 @@\n te\n-s\n+x\n t\n' }]"
		);
		let res = parse_val!("{ test: { other: null, something: 123 }, temp: 'text' }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_copy_simple() {
		let mut val = parse_val!("{ test: 123, temp: true }");
		let ops = parse_val!("[{ op: 'copy', path: '/temp', from: '/test' }]");
		let res = parse_val!("{ test: 123, temp: 123 }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_move_simple() {
		let mut val = parse_val!("{ temp: true, some: 123 }");
		let ops = parse_val!("[{ op: 'move', path: '/other', from: '/temp' }]");
		let res = parse_val!("{ other: true, some: 123 }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_test_simple() {
		let mut val = parse_val!("{ test: { other: 'test', something: 123 }, temp: true }");
		let ops = parse_val!(
			"[{ op: 'remove', path: '/test/something' }, { op: 'test', path: '/temp', value: true }]"
		);
		let res = parse_val!("{ test: { other: 'test' }, temp: true }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_add_embedded() {
		let mut val = parse_val!("{ test: { other: null, something: 123 } }");
		let ops = parse_val!("[{ op: 'add', path: '/temp/test', value: true }]");
		let res = parse_val!("{ test: { other: null, something: 123 }, temp: { test: true } }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_remove_embedded() {
		let mut val = parse_val!("{ test: { other: null, something: 123 }, temp: true }");
		let ops = parse_val!("[{ op: 'remove', path: '/test/other' }]");
		let res = parse_val!("{ test: { something: 123 }, temp: true }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_remove_array_index() {
		let mut val = parse_val!("{ id: todo:1 }");
		let add = parse_val!("[{ op: 'add', path: '/list', value: ['Item here'] }]");
		let remove = parse_val!("[{ op: 'remove', path: '/list/0' }]");
		let res = parse_val!("{ id: todo:1, list: [] }");
		val.patch(add).unwrap();
		val.patch(remove).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_add_array_index_append_at_length() {
		// RFC 6902 ยง4.1: an index equal to the array length appends.
		let mut val = parse_val!("{ list: ['a', 'b'] }");
		let ops = parse_val!("[{ op: 'add', path: '/list/2', value: 'c' }]");
		let res = parse_val!("{ list: ['a', 'b', 'c'] }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_add_array_index_out_of_bounds_errors() {
		// RFC 6902 ยง4.1: an index greater than the array length is invalid.
		let mut val = parse_val!("{ list: ['a', 'b'] }");
		let ops = parse_val!("[{ op: 'add', path: '/list/5', value: 'c' }]");
		let err = val.patch(ops).unwrap_err();
		let msg = err.to_string();
		assert!(
			msg.contains("index 5 is out of bounds for array of length 2"),
			"unexpected error message: {msg}"
		);
		// The value must be unchanged when a patch op fails.
		assert_eq!(val, parse_val!("{ list: ['a', 'b'] }"));
	}

	#[tokio::test]
	async fn patch_replace_embedded() {
		let mut val = parse_val!("{ test: { other: null, something: 123 }, temp: true }");
		let ops = parse_val!("[{ op: 'replace', path: '/test/other', value: 'text' }]");
		let res = parse_val!("{ test: { other: 'text', something: 123 }, temp: true }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_change_embedded() {
		let mut val = parse_val!("{ test: { other: 'test', something: 123 }, temp: true }");
		let ops = parse_val!(
			"[{ op: 'change', path: '/test/other', value: '@@ -1,4 +1,4 @@\n te\n-s\n+x\n t\n' }]"
		);
		let res = parse_val!("{ test: { other: 'text', something: 123 }, temp: true }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_copy_embedded() {
		let mut val = parse_val!("{ test: { other: null }, temp: 123 }");
		let ops = parse_val!("[{ op: 'copy', path: '/test/other', from: '/temp' }]");
		let res = parse_val!("{ test: { other: 123 }, temp: 123 }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_move_embedded() {
		let mut val = parse_val!("{ test: { other: ':3', some: 123 }}");
		let ops = parse_val!("[{ op: 'move', path: '/temp', from: '/test/other' }]");
		let res = parse_val!("{ test: { some: 123 }, temp: ':3' }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_test_embedded() {
		let mut val = parse_val!("{ test: { other: 'test', something: 123 }, temp: true }");
		let ops = parse_val!(
			"[{ op: 'remove', path: '/test/other' }, { op: 'test', path: '/test/something', value: 123 }]"
		);
		let res = parse_val!("{ test: { something: 123 }, temp: true }");
		val.patch(ops).unwrap();
		assert_eq!(res, val);
	}

	#[tokio::test]
	async fn patch_change_invalid() {
		// See https://github.com/surrealdb/surrealdb/issues/2001
		let mut val = parse_val!("{ test: { other: 'test', something: 123 }, temp: true }");
		let ops = parse_val!("[{ op: 'change', path: '/test/other', value: 'text' }]");
		assert!(val.patch(ops).is_err());
	}

	#[tokio::test]
	async fn patch_test_invalid() {
		let mut val = parse_val!("{ test: { other: 'test', something: 123 }, temp: true }");
		let should = val.clone();
		let ops = parse_val!(
			"[{ op: 'remove', path: '/test/other' }, { op: 'test', path: '/test/something', value: 'not same' }]"
		);
		assert!(val.patch(ops).is_err());
		// It is important to test if patches applied even if test operation fails
		assert_eq!(val, should);
	}

	#[tokio::test]
	async fn patch_change_root() {
		// Issue 7239: empty-path patch ops must target the root value.
		let mut val = parse_val!("'Hello'");
		let ops = parse_val!(
			"[{ op: 'change', path: '', value: '@@ -1,5 +1,12 @@\n Hello\n+ there!\n' }]"
		);
		val.patch(ops).unwrap();
		assert_eq!(val, parse_val!("'Hello there!'"));
	}

	#[tokio::test]
	async fn patch_replace_root() {
		let mut val = parse_val!("1");
		let ops = parse_val!("[{ op: 'replace', path: '', value: 2 }]");
		val.patch(ops).unwrap();
		assert_eq!(val, parse_val!("2"));
	}

	#[tokio::test]
	async fn patch_diff_roundtrip_string_root() {
		let mut start = parse_val!("'Hello'");
		let after = parse_val!("'Hello there!'");
		let ops = Operation::operations_to_value(start.diff(&after));
		start.patch(ops).unwrap();
		assert_eq!(start, after);
	}

	#[tokio::test]
	async fn patch_diff_roundtrip_number_root() {
		let mut start = parse_val!("1");
		let after = parse_val!("2");
		let ops = Operation::operations_to_value(start.diff(&after));
		start.patch(ops).unwrap();
		assert_eq!(start, after);
	}
}