surrealdb_core/rpc/
rpc_context.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
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
use crate::err::Error;
use std::{collections::BTreeMap, mem};

#[cfg(all(not(target_family = "wasm"), surrealdb_unstable))]
use async_graphql::BatchRequest;
use uuid::Uuid;

#[cfg(all(not(target_family = "wasm"), surrealdb_unstable))]
use crate::dbs::capabilities::ExperimentalTarget;
#[cfg(all(not(target_family = "wasm"), surrealdb_unstable))]
use crate::gql::SchemaCache;
use crate::{
	dbs::{capabilities::MethodTarget, QueryType, Response, Session},
	kvs::Datastore,
	rpc::args::Take,
	sql::{
		statements::{
			CreateStatement, DeleteStatement, InsertStatement, KillStatement, LiveStatement,
			RelateStatement, SelectStatement, UpdateStatement, UpsertStatement,
		},
		Array, Fields, Function, Model, Output, Query, Strand, Value,
	},
};

use super::{method::Method, response::Data, rpc_error::RpcError};

#[allow(async_fn_in_trait)]
pub trait RpcContext {
	/// The datastore for this RPC interface
	fn kvs(&self) -> &Datastore;
	/// The current session for this RPC context
	fn session(&self) -> &Session;
	/// Mutable access to the current session for this RPC context
	fn session_mut(&mut self) -> &mut Session;
	/// The current parameters stored on this RPC context
	fn vars(&self) -> &BTreeMap<String, Value>;
	/// Mutable access to the current parameters stored on this RPC context
	fn vars_mut(&mut self) -> &mut BTreeMap<String, Value>;
	/// The version information for this RPC context
	fn version_data(&self) -> Data;

	// ------------------------------
	// Realtime
	// ------------------------------

	/// Live queries are disabled by default
	const LQ_SUPPORT: bool = false;

	/// Handles the execution of a LIVE statement
	fn handle_live(&self, _lqid: &Uuid) -> impl std::future::Future<Output = ()> + Send {
		async { unimplemented!("handle_live function must be implemented if LQ_SUPPORT = true") }
	}
	/// Handles the execution of a KILL statement
	fn handle_kill(&self, _lqid: &Uuid) -> impl std::future::Future<Output = ()> + Send {
		async { unimplemented!("handle_kill function must be implemented if LQ_SUPPORT = true") }
	}
	/// Handles the cleanup of live queries
	fn cleanup_lqs(&self) -> impl std::future::Future<Output = ()> + Send {
		async { unimplemented!("cleanup_lqs function must be implemented if LQ_SUPPORT = true") }
	}

	// ------------------------------
	// GraphQL
	// ------------------------------

	/// GraphQL queries are disabled by default
	#[cfg(all(not(target_family = "wasm"), surrealdb_unstable))]
	const GQL_SUPPORT: bool = false;

	/// Returns the GraphQL schema cache used in GraphQL queries
	#[cfg(all(not(target_family = "wasm"), surrealdb_unstable))]
	fn graphql_schema_cache(&self) -> &SchemaCache {
		unimplemented!("graphql_schema_cache function must be implemented if GQL_SUPPORT = true")
	}

	// ------------------------------
	// Method execution
	// ------------------------------

	/// Executes any method on this RPC implementation
	async fn execute_mutable(&mut self, method: Method, params: Array) -> Result<Data, RpcError> {
		// Check if capabilities allow executing the requested RPC method
		if !self.kvs().allows_rpc_method(&MethodTarget {
			method,
		}) {
			warn!("Capabilities denied RPC method call attempt, target: '{}'", method.to_str());
			return Err(RpcError::MethodNotAllowed);
		}
		// Execute the desired method
		match method {
			Method::Ping => Ok(Value::None.into()),
			Method::Info => self.info().await,
			Method::Use => self.yuse(params).await,
			Method::Signup => self.signup(params).await,
			Method::Signin => self.signin(params).await,
			Method::Authenticate => self.authenticate(params).await,
			Method::Invalidate => self.invalidate().await,
			Method::Reset => self.reset().await,
			Method::Kill => self.kill(params).await,
			Method::Live => self.live(params).await,
			Method::Set => self.set(params).await,
			Method::Unset => self.unset(params).await,
			Method::Select => self.select(params).await,
			Method::Insert => self.insert(params).await,
			Method::Create => self.create(params).await,
			Method::Upsert => self.upsert(params).await,
			Method::Update => self.update(params).await,
			Method::Merge => self.merge(params).await,
			Method::Patch => self.patch(params).await,
			Method::Delete => self.delete(params).await,
			Method::Version => self.version(params).await,
			Method::Query => self.query(params).await,
			Method::Relate => self.relate(params).await,
			Method::Run => self.run(params).await,
			Method::GraphQL => self.graphql(params).await,
			Method::InsertRelation => self.insert_relation(params).await,
			Method::Unknown => Err(RpcError::MethodNotFound),
		}
	}

	/// Executes any immutable method on this RPC implementation
	async fn execute_immutable(&self, method: Method, params: Array) -> Result<Data, RpcError> {
		// Check if capabilities allow executing the requested RPC method
		if !self.kvs().allows_rpc_method(&MethodTarget {
			method,
		}) {
			warn!("Capabilities denied RPC method call attempt, target: '{}'", method.to_str());
			return Err(RpcError::MethodNotAllowed);
		}
		// Execute the desired method
		match method {
			Method::Ping => Ok(Value::None.into()),
			Method::Info => self.info().await,
			Method::Select => self.select(params).await,
			Method::Insert => self.insert(params).await,
			Method::Create => self.create(params).await,
			Method::Upsert => self.upsert(params).await,
			Method::Update => self.update(params).await,
			Method::Merge => self.merge(params).await,
			Method::Patch => self.patch(params).await,
			Method::Delete => self.delete(params).await,
			Method::Version => self.version(params).await,
			Method::Query => self.query(params).await,
			Method::Relate => self.relate(params).await,
			Method::Run => self.run(params).await,
			Method::GraphQL => self.graphql(params).await,
			Method::InsertRelation => self.insert_relation(params).await,
			Method::Unknown => Err(RpcError::MethodNotFound),
			_ => Err(RpcError::MethodNotFound),
		}
	}

	// ------------------------------
	// Methods for authentication
	// ------------------------------

	async fn yuse(&mut self, params: Array) -> Result<Data, RpcError> {
		// For both ns+db, string = change, null = unset, none = do nothing
		// We need to be able to adjust either ns or db without affecting the other
		// To be able to select a namespace, and then list resources in that namespace, as an example
		let (ns, db) = params.needs_two()?;
		// Update the selected namespace
		match ns {
			Value::None => (),
			Value::Null => self.session_mut().ns = None,
			Value::Strand(ns) => self.session_mut().ns = Some(ns.0),
			_ => {
				return Err(RpcError::InvalidParams);
			}
		}
		// Update the selected database
		match db {
			Value::None => (),
			Value::Null => self.session_mut().db = None,
			Value::Strand(db) => self.session_mut().db = Some(db.0),
			_ => {
				return Err(RpcError::InvalidParams);
			}
		}
		// Clear any residual database
		if self.session().ns.is_none() && self.session().db.is_some() {
			self.session_mut().db = None;
		}
		// Return nothing
		Ok(Value::None.into())
	}

	// TODO(gguillemas): Update this method in 3.0.0 to return an object instead of a string.
	// This will allow returning refresh tokens as well as any additional credential resulting from signing up.
	async fn signup(&mut self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok(Value::Object(v)) = params.needs_one() else {
			return Err(RpcError::InvalidParams);
		};
		// Take ownership over the current session
		let mut session = mem::take(self.session_mut());
		// Attempt signup, storing information in the session
		let out: Result<Value, Error> =
			crate::iam::signup::signup(self.kvs(), &mut session, v).await.map(|v| v.token.into());
		// Return ownership of the current session
		*self.session_mut() = session;
		// Return the signup result
		out.map(Into::into).map_err(Into::into)
	}

	// TODO(gguillemas): Update this method in 3.0.0 to return an object instead of a string.
	// This will allow returning refresh tokens as well as any additional credential resulting from signing in.
	async fn signin(&mut self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok(Value::Object(v)) = params.needs_one() else {
			return Err(RpcError::InvalidParams);
		};
		// Take ownership over the current session
		let mut session = mem::take(self.session_mut());
		// Attempt signin, storing information in the session
		let out: Result<Value, Error> = crate::iam::signin::signin(self.kvs(), &mut session, v)
			.await
			// The default `signin` method just returns the token
			.map(|v| v.token.into());
		// Return ownership of the current session
		*self.session_mut() = session;
		// Return the signin result
		out.map(Into::into).map_err(Into::into)
	}

	async fn authenticate(&mut self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok(Value::Strand(token)) = params.needs_one() else {
			return Err(RpcError::InvalidParams);
		};
		// Take ownership over the current session
		let mut session = mem::take(self.session_mut());
		// Attempt authentcation, storing information in the session
		let out: Result<Value, Error> =
			crate::iam::verify::token(self.kvs(), &mut session, &token.0)
				.await
				.map(|_| Value::None);
		// Return ownership of the current session
		*self.session_mut() = session;
		// Return nothing on success
		out.map_err(Into::into).map(Into::into)
	}

	async fn invalidate(&mut self) -> Result<Data, RpcError> {
		// Clear the current session
		crate::iam::clear::clear(self.session_mut())?;
		// Return nothing on success
		Ok(Value::None.into())
	}

	async fn reset(&mut self) -> Result<Data, RpcError> {
		// Take ownership over the current session
		let mut session = mem::take(self.session_mut());
		// Clear the current session completely
		crate::iam::clear::clear(&mut session)?;
		// Clear the namespace and database
		self.session_mut().ns = None;
		self.session_mut().db = None;
		// Clear all connection parameters
		self.vars_mut().clear();
		// Cleanup live queries
		self.cleanup_lqs().await;
		// Return nothing on success
		Ok(Value::None.into())
	}

	// ------------------------------
	// Methods for identification
	// ------------------------------

	async fn info(&self) -> Result<Data, RpcError> {
		// Specify the SQL query string
		let sql = SelectStatement {
			expr: Fields::all(),
			what: vec![Value::Param("auth".into())].into(),
			..Default::default()
		}
		.into();
		// Execute the query on the database
		let mut res = self.kvs().process(sql, self.session(), None).await?;
		// Extract the first value from the result
		Ok(res.remove(0).result?.first().into())
	}

	// ------------------------------
	// Methods for setting variables
	// ------------------------------

	async fn set(&mut self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok((Value::Strand(key), val)) = params.needs_one_or_two() else {
			return Err(RpcError::InvalidParams);
		};
		// Specify the query parameters
		let var = Some(map! {
			key.0.clone() => Value::None,
			=> &self.vars()
		});
		// Compute the specified parameter
		match self.kvs().compute(val, self.session(), var).await? {
			// Remove the variable if undefined
			Value::None => self.vars_mut().remove(&key.0),
			// Store the variable if defined
			v => self.vars_mut().insert(key.0, v),
		};
		// Return nothing
		Ok(Value::Null.into())
	}

	async fn unset(&mut self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok(Value::Strand(key)) = params.needs_one() else {
			return Err(RpcError::InvalidParams);
		};
		// Remove the set parameter
		self.vars_mut().remove(&key.0);
		// Return nothing
		Ok(Value::Null.into())
	}

	// ------------------------------
	// Methods for live queries
	// ------------------------------

	async fn kill(&mut self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let id = params.needs_one()?;
		// Specify the SQL query string
		let sql = KillStatement {
			id,
		}
		.into();
		// Specify the query parameters
		let var = Some(self.vars().clone());
		// Execute the query on the database
		let mut res = self.query_inner(Value::Query(sql), var).await?;
		// Extract the first query result
		Ok(res.remove(0).result?.into())
	}

	async fn live(&mut self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let (what, diff) = params.needs_one_or_two()?;
		// Specify the SQL query string
		let sql = LiveStatement::new_from_what_expr(
			match diff.is_true() {
				true => Fields::default(),
				false => Fields::all(),
			},
			what.could_be_table(),
		)
		.into();
		// Specify the query parameters
		let var = Some(self.vars().clone());
		// Execute the query on the database
		let mut res = self.query_inner(Value::Query(sql), var).await?;
		// Extract the first query result
		Ok(res.remove(0).result?.into())
	}

	// ------------------------------
	// Methods for selecting
	// ------------------------------

	async fn select(&self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok(what) = params.needs_one() else {
			return Err(RpcError::InvalidParams);
		};
		// Specify the SQL query string
		let sql = SelectStatement {
			only: what.is_thing_single(),
			expr: Fields::all(),
			what: vec![what.could_be_table()].into(),
			..Default::default()
		}
		.into();
		// Specify the query parameters
		let var = Some(self.vars().clone());
		// Execute the query on the database
		let mut res = self.kvs().process(sql, self.session(), var).await?;
		// Extract the first query result
		Ok(res
			.remove(0)
			.result
			.or_else(|e| match e {
				Error::SingleOnlyOutput => Ok(Value::None),
				e => Err(e),
			})?
			.into())
	}

	// ------------------------------
	// Methods for inserting
	// ------------------------------

	async fn insert(&self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok((what, data)) = params.needs_two() else {
			return Err(RpcError::InvalidParams);
		};
		// Specify the SQL query string
		let sql = InsertStatement {
			into: match what.is_none_or_null() {
				false => Some(what.could_be_table()),
				true => None,
			},
			data: crate::sql::Data::SingleExpression(data),
			output: Some(Output::After),
			..Default::default()
		}
		.into();
		// Specify the query parameters
		let var = Some(self.vars().clone());
		// Execute the query on the database
		let mut res = self.kvs().process(sql, self.session(), var).await?;
		// Extract the first query result
		Ok(res
			.remove(0)
			.result
			.or_else(|e| match e {
				Error::SingleOnlyOutput => Ok(Value::None),
				e => Err(e),
			})?
			.into())
	}

	async fn insert_relation(&self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok((what, data)) = params.needs_two() else {
			return Err(RpcError::InvalidParams);
		};
		// Specify the SQL query string
		let sql = InsertStatement {
			relation: true,
			into: match what.is_none_or_null() {
				false => Some(what.could_be_table()),
				true => None,
			},
			data: crate::sql::Data::SingleExpression(data),
			output: Some(Output::After),
			..Default::default()
		}
		.into();
		// Specify the query parameters
		let var = Some(self.vars().clone());
		// Execute the query on the database
		let mut res = self.kvs().process(sql, self.session(), var).await?;
		// Extract the first query result
		Ok(res
			.remove(0)
			.result
			.or_else(|e| match e {
				Error::SingleOnlyOutput => Ok(Value::None),
				e => Err(e),
			})?
			.into())
	}

	// ------------------------------
	// Methods for creating
	// ------------------------------

	async fn create(&self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok((what, data)) = params.needs_one_or_two() else {
			return Err(RpcError::InvalidParams);
		};
		let what = what.could_be_table();
		// Specify the SQL query string
		let sql = CreateStatement {
			only: what.is_thing_single() || what.is_table(),
			what: vec![what.could_be_table()].into(),
			data: match data.is_none_or_null() {
				false => Some(crate::sql::Data::ContentExpression(data)),
				true => None,
			},
			output: Some(Output::After),
			..Default::default()
		}
		.into();
		// Specify the query parameters
		let var = Some(self.vars().clone());
		// Execute the query on the database
		let mut res = self.kvs().process(sql, self.session(), var).await?;
		// Extract the first query result
		Ok(res
			.remove(0)
			.result
			.or_else(|e| match e {
				Error::SingleOnlyOutput => Ok(Value::None),
				e => Err(e),
			})?
			.into())
	}

	// ------------------------------
	// Methods for upserting
	// ------------------------------

	async fn upsert(&self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok((what, data)) = params.needs_one_or_two() else {
			return Err(RpcError::InvalidParams);
		};
		// Specify the SQL query string
		let sql = UpsertStatement {
			only: what.is_thing_single(),
			what: vec![what.could_be_table()].into(),
			data: match data.is_none_or_null() {
				false => Some(crate::sql::Data::ContentExpression(data)),
				true => None,
			},
			output: Some(Output::After),
			..Default::default()
		}
		.into();
		// Specify the query parameters
		let var = Some(self.vars().clone());
		// Execute the query on the database
		let mut res = self.kvs().process(sql, self.session(), var).await?;
		// Extract the first query result
		Ok(res
			.remove(0)
			.result
			.or_else(|e| match e {
				Error::SingleOnlyOutput => Ok(Value::None),
				e => Err(e),
			})?
			.into())
	}

	// ------------------------------
	// Methods for updating
	// ------------------------------

	async fn update(&self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok((what, data)) = params.needs_one_or_two() else {
			return Err(RpcError::InvalidParams);
		};
		// Specify the SQL query string
		let sql = UpdateStatement {
			only: what.is_thing_single(),
			what: vec![what.could_be_table()].into(),
			data: match data.is_none_or_null() {
				false => Some(crate::sql::Data::ContentExpression(data)),
				true => None,
			},
			output: Some(Output::After),
			..Default::default()
		}
		.into();
		// Specify the query parameters
		let var = Some(self.vars().clone());
		// Execute the query on the database
		let mut res = self.kvs().process(sql, self.session(), var).await?;
		// Extract the first query result
		Ok(res
			.remove(0)
			.result
			.or_else(|e| match e {
				Error::SingleOnlyOutput => Ok(Value::None),
				e => Err(e),
			})?
			.into())
	}

	// ------------------------------
	// Methods for merging
	// ------------------------------

	async fn merge(&self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok((what, data)) = params.needs_one_or_two() else {
			return Err(RpcError::InvalidParams);
		};
		// Specify the SQL query string
		let sql = UpdateStatement {
			only: what.is_thing_single(),
			what: vec![what.could_be_table()].into(),
			data: match data.is_none_or_null() {
				false => Some(crate::sql::Data::MergeExpression(data)),
				true => None,
			},
			output: Some(Output::After),
			..Default::default()
		}
		.into();
		// Specify the query parameters
		let var = Some(self.vars().clone());
		// Execute the query on the database
		let mut res = self.kvs().process(sql, self.session(), var).await?;
		// Extract the first query result
		Ok(res
			.remove(0)
			.result
			.or_else(|e| match e {
				Error::SingleOnlyOutput => Ok(Value::None),
				e => Err(e),
			})?
			.into())
	}

	// ------------------------------
	// Methods for patching
	// ------------------------------

	async fn patch(&self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok((what, data, diff)) = params.needs_one_two_or_three() else {
			return Err(RpcError::InvalidParams);
		};
		// Specify the SQL query string
		let sql = UpdateStatement {
			only: what.is_thing_single(),
			what: vec![what.could_be_table()].into(),
			data: Some(crate::sql::Data::PatchExpression(data)),
			output: match diff.is_true() {
				true => Some(Output::Diff),
				false => Some(Output::After),
			},
			..Default::default()
		}
		.into();
		// Specify the query parameters
		let var = Some(self.vars().clone());
		// Execute the query on the database
		let mut res = self.kvs().process(sql, self.session(), var).await?;
		// Extract the first query result
		Ok(res
			.remove(0)
			.result
			.or_else(|e| match e {
				Error::SingleOnlyOutput => Ok(Value::None),
				e => Err(e),
			})?
			.into())
	}

	// ------------------------------
	// Methods for relating
	// ------------------------------

	async fn relate(&self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok((from, kind, with, data)) = params.needs_three_or_four() else {
			return Err(RpcError::InvalidParams);
		};
		// Specify the SQL query string
		let sql = RelateStatement {
			only: from.is_single() && with.is_single(),
			from,
			kind: kind.could_be_table(),
			with,
			data: match data.is_none_or_null() {
				false => Some(crate::sql::Data::ContentExpression(data)),
				true => None,
			},
			output: Some(Output::After),
			..Default::default()
		}
		.into();
		// Specify the query parameters
		let var = Some(self.vars().clone());
		// Execute the query on the database
		let mut res = self.kvs().process(sql, self.session(), var).await?;
		// Extract the first query result
		Ok(res
			.remove(0)
			.result
			.or_else(|e| match e {
				Error::SingleOnlyOutput => Ok(Value::None),
				e => Err(e),
			})?
			.into())
	}

	// ------------------------------
	// Methods for deleting
	// ------------------------------

	async fn delete(&self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok(what) = params.needs_one() else {
			return Err(RpcError::InvalidParams);
		};
		// Specify the SQL query string
		let sql = DeleteStatement {
			only: what.is_thing_single(),
			what: vec![what.could_be_table()].into(),
			output: Some(Output::Before),
			..Default::default()
		}
		.into();
		// Specify the query parameters
		let var = Some(self.vars().clone());
		// Execute the query on the database
		let mut res = self.kvs().process(sql, self.session(), var).await?;
		// Extract the first query result
		Ok(res
			.remove(0)
			.result
			.or_else(|e| match e {
				Error::SingleOnlyOutput => Ok(Value::None),
				e => Err(e),
			})?
			.into())
	}

	// ------------------------------
	// Methods for getting info
	// ------------------------------

	async fn version(&self, params: Array) -> Result<Data, RpcError> {
		match params.len() {
			0 => Ok(self.version_data()),
			_ => Err(RpcError::InvalidParams),
		}
	}

	// ------------------------------
	// Methods for querying
	// ------------------------------

	async fn query(&self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok((query, vars)) = params.needs_one_or_two() else {
			return Err(RpcError::InvalidParams);
		};
		// Check the query input type
		if !(query.is_query() || query.is_strand()) {
			return Err(RpcError::InvalidParams);
		}
		// Specify the query variables
		let vars = match vars {
			Value::Object(mut v) => Some(mrg! {v.0, &self.vars()}),
			Value::None | Value::Null => Some(self.vars().clone()),
			_ => return Err(RpcError::InvalidParams),
		};
		// Execute the specified query
		self.query_inner(query, vars).await.map(Into::into)
	}

	// ------------------------------
	// Methods for running functions
	// ------------------------------

	async fn run(&self, params: Array) -> Result<Data, RpcError> {
		// Process the method arguments
		let Ok((name, version, args)) = params.needs_one_two_or_three() else {
			return Err(RpcError::InvalidParams);
		};
		// Parse the function name argument
		let name = match name {
			Value::Strand(Strand(v)) => v,
			_ => return Err(RpcError::InvalidParams),
		};
		// Parse any function version argument
		let version = match version {
			Value::Strand(Strand(v)) => Some(v),
			Value::None | Value::Null => None,
			_ => return Err(RpcError::InvalidParams),
		};
		// Parse the function arguments if specified
		let args = match args {
			Value::Array(Array(arr)) => arr,
			Value::None | Value::Null => vec![],
			_ => return Err(RpcError::InvalidParams),
		};
		// Specify the function to run
		let func: Query = match &name[0..4] {
			"fn::" => Function::Custom(name.chars().skip(4).collect(), args).into(),
			"ml::" => Model {
				name: name.chars().skip(4).collect(),
				version: version.ok_or(RpcError::InvalidParams)?,
				args,
			}
			.into(),
			_ => Function::Normal(name, args).into(),
		};
		// Specify the query variables
		let vars = Some(self.vars().clone());
		// Execute the function on the database
		let mut res = self.kvs().process(func, self.session(), vars).await?;
		// Extract the first query result
		Ok(res.remove(0).result?.into())
	}

	// ------------------------------
	// Methods for querying with GraphQL
	// ------------------------------

	#[cfg(any(target_family = "wasm", not(surrealdb_unstable)))]
	async fn graphql(&self, _: Array) -> Result<Data, RpcError> {
		Err(RpcError::MethodNotFound)
	}

	#[cfg(all(not(target_family = "wasm"), surrealdb_unstable))]
	async fn graphql(&self, params: Array) -> Result<Data, RpcError> {
		if !self.kvs().get_capabilities().allows_experimental(&ExperimentalTarget::GraphQL) {
			return Err(RpcError::BadGQLConfig);
		}

		use serde::Serialize;

		use crate::gql;

		if !Self::GQL_SUPPORT {
			return Err(RpcError::BadGQLConfig);
		}

		let Ok((query, options)) = params.needs_one_or_two() else {
			return Err(RpcError::InvalidParams);
		};

		enum GraphQLFormat {
			Json,
		}

		// Default to compressed output
		let mut pretty = false;
		// Default to graphql json format
		let mut format = GraphQLFormat::Json;
		// Process any secondary config options
		match options {
			// A config object was passed
			Value::Object(o) => {
				for (k, v) in o {
					match (k.as_str(), v) {
						("pretty", Value::Bool(b)) => pretty = b,
						("format", Value::Strand(s)) => match s.as_str() {
							"json" => format = GraphQLFormat::Json,
							_ => return Err(RpcError::InvalidParams),
						},
						_ => return Err(RpcError::InvalidParams),
					}
				}
			}
			// The config argument was not supplied
			Value::None => (),
			// An invalid config argument was received
			_ => return Err(RpcError::InvalidParams),
		}
		// Process the graphql query argument
		let req = match query {
			// It is a string, so parse the query
			Value::Strand(s) => match format {
				GraphQLFormat::Json => {
					let tmp: BatchRequest =
						serde_json::from_str(s.as_str()).map_err(|_| RpcError::ParseError)?;
					tmp.into_single().map_err(|_| RpcError::ParseError)?
				}
			},
			// It is an object, so build the query
			Value::Object(mut o) => {
				// We expect a `query` key with the graphql query
				let mut tmp = match o.remove("query") {
					Some(Value::Strand(s)) => async_graphql::Request::new(s),
					_ => return Err(RpcError::InvalidParams),
				};
				// We can accept a `variables` key with graphql variables
				match o.remove("variables").or(o.remove("vars")) {
					Some(obj @ Value::Object(_)) => {
						let gql_vars = gql::schema::sql_value_to_gql_value(obj)
							.map_err(|_| RpcError::InvalidRequest)?;

						tmp = tmp.variables(async_graphql::Variables::from_value(gql_vars));
					}
					Some(_) => return Err(RpcError::InvalidParams),
					None => {}
				}
				// We can accept an `operation` key with a graphql operation name
				match o.remove("operationName").or(o.remove("operation")) {
					Some(Value::Strand(s)) => tmp = tmp.operation_name(s),
					Some(_) => return Err(RpcError::InvalidParams),
					None => {}
				}
				// Return the graphql query object
				tmp
			}
			// We received an invalid graphql query
			_ => return Err(RpcError::InvalidParams),
		};
		// Process and cache the graphql schema
		let schema = self
			.graphql_schema_cache()
			.get_schema(self.session())
			.await
			.map_err(|e| RpcError::Thrown(e.to_string()))?;
		// Execute the request against the schema
		let res = schema.execute(req).await;
		// Serialize the graphql response
		let out = match pretty {
			true => {
				let mut buf = Vec::new();
				let formatter = serde_json::ser::PrettyFormatter::with_indent(b"    ");
				let mut ser = serde_json::Serializer::with_formatter(&mut buf, formatter);
				res.serialize(&mut ser).ok().and_then(|_| String::from_utf8(buf).ok())
			}
			false => serde_json::to_string(&res).ok(),
		}
		.ok_or(RpcError::Thrown("Serialization Error".to_string()))?;
		// Output the graphql response
		Ok(Value::Strand(out.into()).into())
	}

	// ------------------------------
	// Private methods
	// ------------------------------

	async fn query_inner(
		&self,
		query: Value,
		vars: Option<BTreeMap<String, Value>>,
	) -> Result<Vec<Response>, RpcError> {
		// If no live query handler force realtime off
		if !Self::LQ_SUPPORT && self.session().rt {
			return Err(RpcError::BadLQConfig);
		}
		// Execute the query on the database
		let res = match query {
			Value::Query(sql) => self.kvs().process(sql, self.session(), vars).await?,
			Value::Strand(sql) => self.kvs().execute(&sql, self.session(), vars).await?,
			_ => return Err(fail!("Unexpected query type: {query:?}").into()),
		};

		// Post-process hooks for web layer
		for response in &res {
			// This error should be unreachable because we shouldn't proceed if there's no handler
			self.handle_live_query_results(response).await;
		}
		// Return the result to the client
		Ok(res)
	}

	async fn handle_live_query_results(&self, res: &Response) {
		match &res.query_type {
			QueryType::Live => {
				if let Ok(Value::Uuid(lqid)) = &res.result {
					self.handle_live(&lqid.0).await;
				}
			}
			QueryType::Kill => {
				if let Ok(Value::Uuid(lqid)) = &res.result {
					self.handle_kill(&lqid.0).await;
				}
			}
			_ => {}
		}
	}
}