surrealdb 3.2.4

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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
#![allow(clippy::unwrap_used)]
#![cfg(any(
	feature = "protocol-ws",
	feature = "kv-mem",
	feature = "kv-rocksdb",
	feature = "kv-tikv",
	feature = "kv-surrealkv",
))]

// Tests for running live queries
// Supported by the storage engines and the WS protocol

use std::sync::Arc;
use std::time::Duration;

use futures::{Stream, StreamExt};
use surrealdb::method::QueryStream;
use surrealdb::opt::{Config, Resource};
use surrealdb::types::{Action, RecordId, SurrealValue, Value, object};
use surrealdb::{Notification, Result};
use tokio::sync::RwLock;
use tracing::info;
use ulid::Ulid;

use super::CreateDb;
use crate::api_integration::ApiRecordId;

const LQ_TIMEOUT: Duration = Duration::from_secs(2);
const MAX_NOTIFICATIONS: usize = 100;

pub async fn live_select_table(new_db: impl CreateDb) {
	let config = Config::new();
	let (permit, db) = new_db.create_db(config).await;

	db.use_ns(Ulid::new().to_string()).use_db(Ulid::new().to_string()).await.unwrap();

	{
		let table = format!("table_{}", Ulid::new());
		db.query(format!("DEFINE TABLE {table}")).await.unwrap();

		// Start listening
		let mut users = db.select(&table).live().await.unwrap();

		// Create a record
		let created: Option<ApiRecordId> = db.create(table).await.unwrap();
		// Pull the notification
		let notification: Notification<ApiRecordId> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// The returned record should match the created record
		assert_eq!(created, Some(notification.data.clone()));
		// It should be newly created
		assert_eq!(notification.action, Action::Create);

		// Update the record
		let _: Option<ApiRecordId> = db
			.update(&notification.data.id)
			.content(UpdateContent {
				field: "bar".to_string(),
			})
			.await
			.unwrap();
		// Pull the notification
		let notification: Notification<ApiRecordId> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// It should be updated
		assert_eq!(notification.action, Action::Update);

		// Delete the record
		let _: Option<ApiRecordId> = db.delete(&notification.data.id).await.unwrap();
		// Pull the notification
		let notification: Notification<ApiRecordId> = users.next().await.unwrap().unwrap();
		// It should be deleted
		assert_eq!(notification.action, Action::Delete);
	}

	{
		let table = format!("table_{}", Ulid::new());
		db.query(format!("DEFINE TABLE {table}")).await.unwrap();

		// Start listening
		let mut users = db.select(Resource::from(&table)).live().await.unwrap();

		// Create a record
		db.create(Resource::from(&table)).await.unwrap();
		// Pull the notification
		let notification =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// The returned record should be an object
		assert!(notification.data.is_object());
		// It should be newly created
		assert_eq!(notification.action, Action::Create);
	}

	drop(permit);
}

pub async fn live_select_record_id(new_db: impl CreateDb) {
	let config = Config::new();
	let (permit, db) = new_db.create_db(config).await;

	db.use_ns(Ulid::new().to_string()).use_db(Ulid::new().to_string()).await.unwrap();

	{
		let table = format!("table_{}", Ulid::new());
		db.query(format!("DEFINE TABLE {table}")).await.unwrap();

		let record_id = RecordId::new(table, "john");

		// Start listening
		let mut users = db.select(&record_id).live().await.unwrap();

		// Create a record
		let created: Option<ApiRecordId> = db.create(record_id).await.unwrap();
		// Pull the notification
		let notification: Notification<ApiRecordId> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// The returned record should match the created record
		assert_eq!(created, Some(notification.data.clone()));
		// It should be newly created
		assert_eq!(notification.action, Action::Create);

		// Update the record
		let _: Option<ApiRecordId> = db
			.update(&notification.data.id)
			.content(UpdateContent {
				field: "bar".to_string(),
			})
			.await
			.unwrap();
		// Pull the notification
		let notification: Notification<ApiRecordId> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// It should be updated
		assert_eq!(notification.action, Action::Update);

		// Delete the record
		let _: Option<ApiRecordId> = db.delete(&notification.data.id).await.unwrap();
		// Pull the notification
		let notification: Notification<ApiRecordId> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// It should be deleted
		assert_eq!(notification.action, Action::Delete);
	}

	{
		let table = format!("table_{}", Ulid::new());
		db.query(format!("DEFINE TABLE {table}")).await.unwrap();

		let record_id = RecordId::new(table, "john");

		// Start listening
		let mut users = db.select(Resource::from(&record_id)).live().await.unwrap();

		// Create a record
		db.create(Resource::from(record_id)).await.unwrap();
		// Pull the notification
		let notification: Notification<Value> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// The returned record should be an object
		assert!(notification.data.is_object());
		// It should be newly created
		assert_eq!(notification.action, Action::Create);
	}

	drop(permit);
}

pub async fn live_select_record_ranges(new_db: impl CreateDb) {
	let config = Config::new();
	let (permit, db) = new_db.create_db(config).await;

	db.use_ns(Ulid::new().to_string()).use_db(Ulid::new().to_string()).await.unwrap();

	{
		let table = format!("table_{}", Ulid::new());
		db.query(format!("DEFINE TABLE {table}")).await.unwrap();

		// Start listening
		let mut users = db.select(&table).range("jane".."john").live().await.unwrap();

		// Create a record
		let created: Option<ApiRecordId> = db.create((table, "jane")).await.unwrap();
		// Pull the notification
		let notification: Notification<ApiRecordId> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// The returned record should match the created record
		assert_eq!(created, Some(notification.data.clone()));
		// It should be newly created
		assert_eq!(notification.action, Action::Create);

		// Update the record
		let _: Option<ApiRecordId> = db
			.update(&notification.data.id)
			.content(UpdateContent {
				field: "bar".to_string(),
			})
			.await
			.unwrap();
		// Pull the notification
		let notification: Notification<ApiRecordId> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// It should be updated
		assert_eq!(notification.action, Action::Update);

		// Delete the record
		let _: Option<ApiRecordId> = db.delete(&notification.data.id).await.unwrap();

		// Pull the notification
		let notification: Notification<ApiRecordId> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();

		// It should be deleted
		assert_eq!(notification.action, Action::Delete);
	}

	{
		let table = format!("table_{}", Ulid::new());
		db.query(format!("DEFINE TABLE {table}")).await.unwrap();

		// Start listening
		let mut users =
			db.select(Resource::from(&table)).range("jane".."john").live().await.unwrap();

		// Create a record
		let created_value = db
			.create(Resource::from((table, "job")))
			.await
			.unwrap()
			.into_array()
			.unwrap()
			.remove(0)
			.into_object()
			.unwrap();

		// Pull the notification
		let notification: Notification<Value> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// The returned record should be an object
		assert!(notification.data.is_object());
		// It should be newly created
		assert_eq!(notification.action, Action::Create);

		// Delete the record
		let thing = match created_value.get("id").unwrap() {
			Value::RecordId(thing) => thing,
			_ => panic!("Expected a thing"),
		};
		db.query("DELETE $item").bind(("item", thing.clone())).await.unwrap();

		// Pull the notification
		let notification: Notification<Value> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();

		// It should be deleted
		assert_eq!(notification.action, Action::Delete);
		let notification = match notification.data {
			Value::Object(notification) => notification,
			_ => panic!("Expected an object"),
		};
		assert_eq!(notification, created_value);
	}

	drop(permit);
}

pub async fn live_select_query(new_db: impl CreateDb) {
	let config = Config::new();
	let (permit, db) = new_db.create_db(config).await;

	db.use_ns(Ulid::new().to_string()).use_db(Ulid::new().to_string()).await.unwrap();
	{
		let table = format!("table_{}", Ulid::new());
		db.query(format!("DEFINE TABLE {table}")).await.unwrap();

		// Start listening
		info!("Starting live query");
		let users: QueryStream<Notification<ApiRecordId>> = db
			.query(format!("LIVE SELECT * FROM {table}"))
			.await
			.unwrap()
			.stream::<Notification<_>>(0)
			.unwrap();
		let users = Arc::new(RwLock::new(users));

		// Create a record
		info!("Creating record");
		let created: Option<ApiRecordId> = db.create(table).await.unwrap();
		// Pull the notification
		let notifications = receive_all_pending_notifications(Arc::clone(&users), LQ_TIMEOUT).await;
		// It should be newly created
		assert_eq!(
			notifications.iter().map(|n| n.action).collect::<Vec<_>>(),
			vec![Action::Create],
			"{:?}",
			notifications
		);
		// The returned record should match the created record
		assert_eq!(created, Some(notifications[0].data.clone()));

		// Update the record
		info!("Updating record");
		let _: Option<ApiRecordId> = db
			.update(&notifications[0].data.id)
			.content(UpdateContent {
				field: "bar".to_string(),
			})
			.await
			.unwrap();
		let notifications = receive_all_pending_notifications(Arc::clone(&users), LQ_TIMEOUT).await;

		// It should be updated
		assert_eq!(
			notifications.iter().map(|n| n.action).collect::<Vec<_>>(),
			[Action::Update],
			"{:?}",
			notifications
		);

		// Delete the record
		info!("Deleting record");
		let _: Option<ApiRecordId> = db.delete(&notifications[0].data.id).await.unwrap();
		// Pull the notification
		let notifications = receive_all_pending_notifications(Arc::clone(&users), LQ_TIMEOUT).await;
		// It should be deleted
		assert_eq!(
			notifications.iter().map(|n| n.action).collect::<Vec<_>>(),
			[Action::Delete],
			"{:?}",
			notifications
		);
	}

	{
		let table = format!("table_{}", Ulid::new());
		db.query(format!("DEFINE TABLE {table} CHANGEFEED 10m INCLUDE ORIGINAL")).await.unwrap();

		// Start listening
		let mut users = db
			.query(format!("LIVE SELECT * FROM {table}"))
			.await
			.unwrap()
			.stream::<Value>(0)
			.unwrap();

		// Create a record
		db.create(Resource::from(&table)).await.unwrap();
		// Pull the notification
		let notification =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();

		// The returned record should be an object
		assert!(notification.data.is_object());
		// It should be newly created
		assert_eq!(notification.action, Action::Create);
	}

	{
		let table = format!("table_{}", Ulid::new());
		db.query(format!("DEFINE TABLE {table} CHANGEFEED 10m INCLUDE ORIGINAL")).await.unwrap();

		// Start listening
		let mut users = db
			.query(format!("LIVE SELECT * FROM {table}"))
			.await
			.unwrap()
			.stream::<Notification<_>>(())
			.unwrap();

		// Create a record
		let created: Option<ApiRecordId> = db.create(table).await.unwrap();
		// Pull the notification
		let notification: Notification<ApiRecordId> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// The returned record should match the created record
		assert_eq!(created, Some(notification.data.clone()));
		// It should be newly created
		assert_eq!(notification.action, Action::Create, "{:?}", notification);

		// Update the record
		let _: Option<ApiRecordId> = db
			.update(&notification.data.id)
			.content(UpdateContent {
				field: "bar".to_string(),
			})
			.await
			.unwrap();
		// Pull the notification
		let notification: Notification<ApiRecordId> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// It should be updated
		assert_eq!(notification.action, Action::Update, "{:?}", notification);

		// Delete the record
		let _: Option<ApiRecordId> = db.delete(&notification.data.id).await.unwrap();
		// Pull the notification
		let notification: Notification<ApiRecordId> =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// It should be deleted
		assert_eq!(notification.action, Action::Delete, "{:?}", notification);
	}

	{
		let table = format!("table_{}", Ulid::new());
		db.query(format!("DEFINE TABLE {table} CHANGEFEED 10m INCLUDE ORIGINAL")).await.unwrap();

		// Start listening
		let mut users = db
			.query(format!("BEGIN; LIVE SELECT * FROM {table}; COMMIT"))
			.await
			.unwrap()
			.stream::<Value>(())
			.unwrap();

		// Create a record
		db.create(Resource::from(&table)).await.unwrap();
		// Pull the notification
		let notification =
			tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
		// The returned record should be an object
		assert!(notification.data.is_object());
		// It should be newly created
		assert_eq!(notification.action, Action::Create);
	}

	drop(permit);
}

pub async fn live_query_delete_notifications(new_db: impl CreateDb) {
	let config = Config::new();
	let (permit, db) = new_db.create_db(config).await;

	db.use_ns(Ulid::new().to_string()).use_db(Ulid::new().to_string()).await.unwrap();

	db.query("DEFINE TABLE bar".to_string()).await.unwrap().check().unwrap();

	let mut stream =
		db.query("LIVE SELECT field FROM bar").await.unwrap().stream::<Value>(0).unwrap();

	db.query("CREATE bar CONTENT { field: 'baz' }").await.unwrap().check().unwrap();
	let notification =
		tokio::time::timeout(LQ_TIMEOUT, stream.next()).await.unwrap().unwrap().unwrap();
	assert_eq!(notification.data, Value::Object(object! { field: "baz" }));
	assert_eq!(notification.action, Action::Create);

	db.query("UPDATE bar MERGE { data: 123 }").await.unwrap().check().unwrap();
	let notification =
		tokio::time::timeout(LQ_TIMEOUT, stream.next()).await.unwrap().unwrap().unwrap();
	assert_eq!(notification.data, Value::Object(object! { field: "baz" }));
	assert_eq!(notification.action, Action::Update);

	db.query("DELETE bar").await.unwrap().check().unwrap();
	let notification =
		tokio::time::timeout(LQ_TIMEOUT, stream.next()).await.unwrap().unwrap().unwrap();
	assert_eq!(notification.data, Value::Object(object! { field: "baz" }));
	assert_eq!(notification.action, Action::Delete);

	drop(permit);
}

#[derive(Debug, Clone, SurrealValue, PartialEq, PartialOrd)]
struct ApiRecordIdWithFetchedLink {
	id: RecordId,
	link: Option<ApiRecordId>,
}

#[derive(Debug, Clone, SurrealValue, PartialEq, PartialOrd)]
struct ApiRecordIdWithUnfetchedLink {
	id: RecordId,
	link: RecordId,
}

#[derive(Debug, Clone, SurrealValue, PartialEq, PartialOrd)]
struct LinkContent {
	link: RecordId,
}

#[derive(Debug, Clone, SurrealValue)]
struct UpdateContent {
	field: String,
}

pub async fn live_select_with_fetch(new_db: impl CreateDb) {
	let config = Config::new();
	let (permit, db) = new_db.create_db(config).await;

	db.use_ns(Ulid::new().to_string()).use_db(Ulid::new().to_string()).await.unwrap();

	let table = format!("table_{}", Ulid::new());
	let linktb = format!("link_{}", Ulid::new());
	db.query(format!("DEFINE TABLE {table}")).await.unwrap();

	// Start listening
	let mut users = db
		.query(format!("LIVE SELECT * FROM {table} FETCH link"))
		.await
		.unwrap()
		.stream::<Notification<_>>(())
		.unwrap();

	let link: Option<ApiRecordId> = db.create(&linktb).await.unwrap();
	let linkone = link.unwrap().id;
	let link: Option<ApiRecordId> = db.create(&linktb).await.unwrap();
	let linktwo = link.unwrap().id;

	// Create a record
	let created: Option<ApiRecordIdWithUnfetchedLink> = db
		.create(table)
		.content(LinkContent {
			link: linkone.clone(),
		})
		.await
		.unwrap();
	// Pull the notification
	let notification: Notification<ApiRecordIdWithFetchedLink> =
		tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
	// // The returned record should match the created record
	assert_eq!(
		ApiRecordIdWithFetchedLink {
			id: created.unwrap().id,
			link: Some(ApiRecordId {
				id: linkone,
			}),
		},
		notification.data.clone()
	);
	// It should be newly created
	assert_eq!(notification.action, Action::Create);

	// Update the record
	let updated: Option<ApiRecordIdWithUnfetchedLink> = db
		.update(&notification.data.id)
		.content(LinkContent {
			link: linktwo.clone(),
		})
		.await
		.unwrap();
	// Pull the notification
	let notification: Notification<ApiRecordIdWithFetchedLink> =
		tokio::time::timeout(LQ_TIMEOUT, users.next()).await.unwrap().unwrap().unwrap();
	// The returned record should match the updated record
	assert_eq!(
		ApiRecordIdWithFetchedLink {
			id: updated.unwrap().id,
			link: Some(ApiRecordId {
				id: linktwo,
			}),
		},
		notification.data.clone()
	);
	// It should be updated
	assert_eq!(notification.action, Action::Update);

	// Delete the record
	let _: Option<ApiRecordIdWithUnfetchedLink> = db.delete(&notification.data.id).await.unwrap();
	// Pull the notification
	let notification: Notification<ApiRecordIdWithFetchedLink> =
		users.next().await.unwrap().unwrap();
	// It should be deleted
	assert_eq!(notification.action, Action::Delete);

	drop(permit);
}

async fn receive_all_pending_notifications<S: Stream<Item = Result<Notification<I>>> + Unpin, I>(
	stream: Arc<RwLock<S>>,
	timeout: Duration,
) -> Vec<Notification<I>> {
	let mut results = Vec::new();
	let we_expect_timeout = tokio::time::timeout(timeout, async {
		while let Some(notification) = stream.write().await.next().await {
			if results.len() >= MAX_NOTIFICATIONS {
				panic!("too many notification!")
			}
			results.push(notification.unwrap())
		}
	})
	.await;
	assert!(we_expect_timeout.is_err());
	results
}

/// Test that LIVE SELECT returns UUID via take() method
/// This is a regression test for https://github.com/surrealdb/surrealdb/issues/6693
pub async fn live_select_returns_uuid(new_db: impl CreateDb) {
	let config = Config::new();
	let (permit, db) = new_db.create_db(config).await;

	db.use_ns(Ulid::new().to_string()).use_db(Ulid::new().to_string()).await.unwrap();

	let table = format!("table_{}", Ulid::new());
	db.query(format!("DEFINE TABLE {table}")).await.unwrap();

	// Execute LIVE SELECT and get the result via take()
	let mut response = db.query(format!("LIVE SELECT * FROM {table}")).await.unwrap();

	// The response should have 1 statement
	assert_eq!(response.num_statements(), 1, "LIVE SELECT should return exactly one result");

	// Take the result - it should be a UUID
	let result: Value = response.take(0).unwrap();
	assert!(result.is_uuid(), "LIVE SELECT should return a UUID, got: {:?}", result);

	drop(permit);
}

define_include_tests!(live => {
	#[test_log::test(tokio::test)]
	live_select_table,
	#[test_log::test(tokio::test)]
	live_select_record_id,
	#[test_log::test(tokio::test)]
	live_select_record_ranges,
	#[test_log::test(tokio::test)]
	live_select_query,
	#[test_log::test(tokio::test)]
	live_select_with_fetch,
	#[test_log::test(tokio::test)]
	live_query_delete_notifications,
	#[test_log::test(tokio::test)]
	live_select_returns_uuid,
});