surrealdb-core 3.2.2

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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
use std::borrow::Cow;

use anyhow::Result;
use reblessive::tree::Stk;
use surrealdb_types::{SqlFormat, ToSql};

use crate::catalog::{Permission, TableDefinition};
use crate::ctx::{Context, FrozenContext};
use crate::dbs::Options;
use crate::doc::CursorDoc;
use crate::expr::cond::Cond;
use crate::expr::data::Data;
use crate::expr::fetch::Fetchs;
use crate::expr::field::Fields;
use crate::expr::group::Groups;
use crate::expr::limit::Limit;
use crate::expr::order::Ordering;
use crate::expr::output::Output;
use crate::expr::parameterize::exprs_to_fields;
use crate::expr::split::Splits;
use crate::expr::start::Start;
use crate::expr::statements::LiveFields;
use crate::expr::statements::access::AccessStatement;
use crate::expr::statements::create::CreateStatement;
use crate::expr::statements::delete::DeleteStatement;
use crate::expr::statements::insert::InsertStatement;
use crate::expr::statements::live::LiveStatement;
use crate::expr::statements::relate::RelateStatement;
use crate::expr::statements::select::SelectStatement;
use crate::expr::statements::show::ShowStatement;
use crate::expr::statements::update::UpdateStatement;
use crate::expr::statements::upsert::UpsertStatement;
use crate::expr::{Explain, Expr, FlowResultExt, Idiom, With};
use crate::idx::planner::QueryPlanner;
use crate::val::Duration;

#[derive(Clone, Debug)]
pub(crate) enum Statement<'a> {
	Live(&'a LiveStatement),
	Show(&'a ShowStatement),
	Select {
		stmt: &'a SelectStatement,
		/// Fields to omit from the result.
		omit: Vec<Idiom>,
		/// Rewritten condition with optimizations (e.g., count(->edge) > 0 -> LIMIT 1).
		/// When present, this replaces `stmt.cond` for evaluation.
		rewritten_cond: Option<Cond>,
	},
	Create(&'a CreateStatement),
	Upsert(&'a UpsertStatement),
	Update(&'a UpdateStatement),
	Relate(&'a RelateStatement),
	Delete(&'a DeleteStatement),
	Insert(&'a InsertStatement),
	Access(&'a AccessStatement),
}

impl<'a> From<&'a LiveStatement> for Statement<'a> {
	fn from(v: &'a LiveStatement) -> Self {
		Statement::Live(v)
	}
}

impl<'a> From<&'a ShowStatement> for Statement<'a> {
	fn from(v: &'a ShowStatement) -> Self {
		Statement::Show(v)
	}
}

impl<'a> From<&'a CreateStatement> for Statement<'a> {
	fn from(v: &'a CreateStatement) -> Self {
		Statement::Create(v)
	}
}

impl<'a> From<&'a UpsertStatement> for Statement<'a> {
	fn from(v: &'a UpsertStatement) -> Self {
		Statement::Upsert(v)
	}
}

impl<'a> From<&'a UpdateStatement> for Statement<'a> {
	fn from(v: &'a UpdateStatement) -> Self {
		Statement::Update(v)
	}
}

impl<'a> From<&'a RelateStatement> for Statement<'a> {
	fn from(v: &'a RelateStatement) -> Self {
		Statement::Relate(v)
	}
}

impl<'a> From<&'a DeleteStatement> for Statement<'a> {
	fn from(v: &'a DeleteStatement) -> Self {
		Statement::Delete(v)
	}
}

impl<'a> From<&'a InsertStatement> for Statement<'a> {
	fn from(v: &'a InsertStatement) -> Self {
		Statement::Insert(v)
	}
}

impl<'a> From<&'a AccessStatement> for Statement<'a> {
	fn from(v: &'a AccessStatement) -> Self {
		Statement::Access(v)
	}
}

impl ToSql for Statement<'_> {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		match self {
			Statement::Live(v) => {
				let sql_stmt: crate::sql::statements::LiveStatement = (*v).clone().into();
				sql_stmt.fmt_sql(f, fmt);
			}
			Statement::Show(v) => {
				let sql_stmt: crate::sql::statements::ShowStatement = (*v).clone().into();
				sql_stmt.fmt_sql(f, fmt);
			}
			Statement::Select {
				stmt,
				..
			} => {
				let sql_stmt: crate::sql::statements::SelectStatement = (*stmt).clone().into();
				sql_stmt.fmt_sql(f, fmt);
			}
			Statement::Create(v) => {
				let sql_stmt: crate::sql::statements::CreateStatement = (*v).clone().into();
				sql_stmt.fmt_sql(f, fmt);
			}
			Statement::Upsert(v) => {
				let sql_stmt: crate::sql::statements::UpsertStatement = (*v).clone().into();
				sql_stmt.fmt_sql(f, fmt);
			}
			Statement::Update(v) => {
				let sql_stmt: crate::sql::statements::UpdateStatement = (*v).clone().into();
				sql_stmt.fmt_sql(f, fmt);
			}
			Statement::Relate(v) => {
				let sql_stmt: crate::sql::statements::RelateStatement = (*v).clone().into();
				sql_stmt.fmt_sql(f, fmt);
			}
			Statement::Delete(v) => {
				let sql_stmt: crate::sql::statements::DeleteStatement = (*v).clone().into();
				sql_stmt.fmt_sql(f, fmt);
			}
			Statement::Insert(v) => {
				let sql_stmt: crate::sql::statements::InsertStatement = (*v).clone().into();
				sql_stmt.fmt_sql(f, fmt);
			}
			Statement::Access(v) => {
				let sql_stmt: crate::sql::statements::AccessStatement = (*v).clone().into();
				sql_stmt.fmt_sql(f, fmt);
			}
		}
	}
}

impl Statement<'_> {
	/// Check if this is a SELECT statement
	pub(crate) fn is_select(&self) -> bool {
		matches!(self, Statement::Select { .. })
	}

	/// Check if this is a CREATE statement
	pub(crate) fn is_create(&self) -> bool {
		matches!(self, Statement::Create(_))
	}

	/// Check if this is a DELETE statement
	pub(crate) fn is_delete(&self) -> bool {
		matches!(self, Statement::Delete(_))
	}

	/// Check if this statement mutates the document storage. CREATE,
	/// UPSERT, UPDATE, RELATE, DELETE, and INSERT all do; SELECT, LIVE,
	/// SHOW, and ACCESS do not. Used by the planner to decide whether to
	/// populate the read-only [`crate::doc::NsDbTbCtx`] or the mutating
	/// [`crate::doc::NsDbTbMutCtx`] when building the per-table catalog
	/// context.
	pub(crate) fn is_mutation(&self) -> bool {
		matches!(
			self,
			Statement::Create(_)
				| Statement::Upsert(_)
				| Statement::Update(_)
				| Statement::Relate(_)
				| Statement::Delete(_)
				| Statement::Insert(_)
		)
	}

	/// Returns whether the document retrieval for
	/// this statement can be deferred. This is used
	/// in the following instances:
	///
	/// CREATE some;
	/// CREATE some:thing;
	/// CREATE |some:1000|;
	/// CREATE |some:1..1000|;
	/// CREATE { id: some:thing };
	/// UPSERT some;
	/// UPSERT some:thing;
	/// UPSERT |some:1000|;
	/// UPSERT |some:1..1000|;
	/// UPSERT { id: some:thing };
	///
	/// Importantly, when a WHERE clause condition is
	/// specified on an UPSERT clause, then we do
	/// first retrieve the document from storage, and
	/// this function will return false in the
	/// following instances:
	///
	/// UPSERT some WHERE test = true;
	/// UPSERT some:thing WHERE test = true;
	/// UPSERT |some:1000| WHERE test = true;
	/// UPSERT |some:1..1000| WHERE test = true;
	/// UPSERT { id: some:thing } WHERE test = true;
	pub(crate) fn is_deferable(&self) -> bool {
		match self {
			Statement::Upsert(v) if v.cond.is_none() => true,
			Statement::Create(_) => true,
			_ => false,
		}
	}

	/// Returns whether the document retrieval for
	/// this statement potentially depends on the
	/// initial value for this document, and can
	/// therefore be retried as an update. This will
	/// be true in the following instances:
	///
	/// UPSERT some UNSET test;
	/// UPSERT some SET test = true;
	/// UPSERT some MERGE { test: true };
	/// UPSERT some PATCH [{ op: 'replace', path: '/', value: { test: true } }];
	/// UPSERT some:thing UNSET test;
	/// UPSERT some:thing SET test = true;
	/// UPSERT some:thing MERGE { test: true };
	/// UPSERT some:thing PATCH [{ op: 'replace', path: '/', value: { test: true
	/// } }]; UPSERT |some:1000| UNSET test;
	/// UPSERT |some:1000| SET test = true;
	/// UPSERT |some:1000| MERGE { test: true };
	/// UPSERT |some:1000| PATCH [{ op: 'replace', path: '/', value: { test:
	/// true } }]; UPSERT |some:1..1000| UNSET test;
	/// UPSERT |some:1..1000| SET test = true;
	/// UPSERT |some:1..1000| MERGE { test: true };
	/// UPSERT |some:1..1000| PATCH [{ op: 'replace', path: '/', value: { test:
	/// true } }];
	///
	/// Importantly, when a WHERE clause condition is
	/// specified on an UPSERT clause, then we do
	/// first retrieve the document from storage, and
	/// this function will return false in the
	/// following instances:
	///
	/// UPSERT some WHERE test = true;
	/// UPSERT some:thing WHERE test = true;
	/// UPSERT |some:1000| WHERE test = true;
	/// UPSERT |some:1..1000| WHERE test = true;
	/// UPSERT { id: some:thing } WHERE test = true;
	pub(crate) fn is_repeatable(&self) -> bool {
		match self {
			Statement::Upsert(v) if v.cond.is_none() => match v.data {
				// We are setting the entire record content
				// so there is no need to fetch the value
				// from the storage engine, if it exists.
				Some(Data::ContentExpression(_)) => false,
				// We are setting the entire record content
				// so there is no need to fetch the value
				// from the storage engine, if it exists.
				Some(Data::ReplaceExpression(_)) => false,
				// We likely have a MERGE or SET clause on
				// this UPSERT statement, and so we might
				// potentially need to access fields from
				// the initial value already existing in
				// the database. Therefore we need to fetch
				// the initial value from storage.
				Some(_) => true,
				// We have no data clause, so we don't need
				// to check if the record exists initially.
				None => false,
			},
			_ => false,
		}
	}

	/// Returns whether the statement requires the table to exist in the database
	/// before executing or if it may be able to create it if it doesn't exist.
	///
	/// SELECT statements, for example, require the table to exist in the database
	/// before executing, regardless of whether the db is strict or not.
	///
	/// UPSERT statements, on the other hand, may be allowed to create the table if it doesn't exist
	/// depending on the db's strictness.
	pub(crate) fn requires_table_existence(&self) -> bool {
		match self {
			Statement::Live(_)
			| Statement::Show(_)
			| Statement::Select {
				..
			}
			| Statement::Update {
				..
			}
			| Statement::Access(_)
			| Statement::Delete(_) => true,
			Statement::Create(_)
			| Statement::Upsert(_)
			| Statement::Relate(_)
			| Statement::Insert(_) => false,
		}
	}

	/// Returns whether the document retrieval for
	/// this statement should attempt to loop over
	/// existing document to update, or is guaranteed
	/// to create a record, if none exists. This is
	/// used in the following instances when the WHERE
	/// clause does not find any matching documents in
	/// the storage engine, and therefore a new record
	/// must be upserted:
	///
	/// UPSERT some WHERE test = true;
	pub(crate) fn is_guaranteed(&self) -> bool {
		matches!(self, Statement::Upsert(v) if v.cond.is_some())
	}

	/// Returns any query fields if specified
	pub(crate) fn expr(&self) -> Option<&Fields> {
		match self {
			Statement::Select {
				stmt,
				..
			} => Some(&stmt.fields),
			Statement::Live(v) => match &v.fields {
				LiveFields::Diff => None,
				LiveFields::Select(x) => Some(x),
			},
			_ => None,
		}
	}

	/// Returns any SET, CONTENT, or MERGE clause if specified
	pub(crate) fn data(&self) -> Option<&Data> {
		match self {
			Statement::Create(v) => v.data.as_ref(),
			Statement::Upsert(v) => v.data.as_ref(),
			Statement::Update(v) => v.data.as_ref(),
			Statement::Relate(v) => v.data.as_ref(),
			Statement::Insert(v) => v.update.as_ref(),
			_ => None,
		}
	}

	/// Returns any WHERE clause if specified
	pub(crate) fn cond(&self) -> Option<&Cond> {
		match self {
			Statement::Live(v) => v.cond.as_ref(),
			Statement::Select {
				stmt,
				rewritten_cond,
				..
			} => rewritten_cond.as_ref().or(stmt.cond.as_ref()),
			Statement::Upsert(v) => v.cond.as_ref(),
			Statement::Update(v) => v.cond.as_ref(),
			Statement::Delete(v) => v.cond.as_ref(),
			_ => None,
		}
	}

	/// Returns any SPLIT clause if specified
	pub(crate) fn split(&self) -> Option<&Splits> {
		match self {
			Statement::Select {
				stmt,
				..
			} => stmt.split.as_ref(),
			_ => None,
		}
	}

	/// Returns any GROUP clause if specified
	pub(crate) fn group(&self) -> Option<&Groups> {
		match self {
			Statement::Select {
				stmt,
				..
			} => stmt.group.as_ref(),
			_ => None,
		}
	}

	/// Returns any ORDER clause if specified
	pub(crate) fn order(&self) -> Option<&Ordering> {
		match self {
			Statement::Select {
				stmt,
				..
			} => stmt.order.as_ref(),
			_ => None,
		}
	}

	/// Returns any WITH clause if specified
	pub(crate) fn with(&self) -> Option<&With> {
		match self {
			Statement::Select {
				stmt,
				..
			} => stmt.with.as_ref(),
			Statement::Update(s) => s.with.as_ref(),
			Statement::Upsert(s) => s.with.as_ref(),
			Statement::Delete(s) => s.with.as_ref(),
			_ => None,
		}
	}

	/// Returns any FETCH clause if specified
	pub(crate) fn fetch(&self) -> Option<&Fetchs> {
		match self {
			Statement::Select {
				stmt,
				..
			} => stmt.fetch.as_ref(),
			_ => None,
		}
	}

	/// Returns any START clause if specified
	pub(crate) fn start(&self) -> Option<&Start> {
		match self {
			Statement::Select {
				stmt,
				..
			} => stmt.start.as_ref(),
			_ => None,
		}
	}

	/// Returns any LIMIT clause if specified
	pub(crate) fn limit(&self) -> Option<&Limit> {
		match self {
			Statement::Select {
				stmt,
				..
			} => stmt.limit.as_ref(),
			_ => None,
		}
	}

	/// Returns any ON DUPLICATE KEY clause if specified
	pub(crate) fn update(&self) -> Option<&Data> {
		match self {
			Statement::Insert(v) => v.update.as_ref(),
			_ => None,
		}
	}

	/// Returns any OMIT fields if specified
	pub(crate) fn omit(&self) -> &[Idiom] {
		match self {
			Statement::Select {
				omit,
				..
			} => omit.as_slice(),
			_ => &[],
		}
	}

	/// Returns whether this statement has an ONLY clause
	pub(crate) fn is_only(&self) -> bool {
		match self {
			Statement::Create(v) => v.only,
			Statement::Delete(v) => v.only,
			Statement::Relate(v) => v.only,
			Statement::Upsert(v) => v.only,
			Statement::Update(v) => v.only,
			Statement::Select {
				stmt,
				..
			} => stmt.only,
			_ => false,
		}
	}

	/// Returns whether this statement has an IGNORE clause
	pub(crate) fn is_ignore(&self) -> bool {
		match self {
			Statement::Insert(v) => v.ignore,
			_ => false,
		}
	}

	/// Returns any RETURN clause if specified
	pub(crate) fn output(&self) -> Option<&Output> {
		match self {
			Statement::Create(v) => v.output.as_ref(),
			Statement::Upsert(v) => v.output.as_ref(),
			Statement::Update(v) => v.output.as_ref(),
			Statement::Relate(v) => v.output.as_ref(),
			Statement::Delete(v) => v.output.as_ref(),
			Statement::Insert(v) => v.output.as_ref(),
			_ => None,
		}
	}

	/// Returns any TEMPFILES clause if specified
	#[cfg(storage)]
	pub(crate) fn tempfiles(&self) -> bool {
		match self {
			Statement::Select {
				stmt,
				..
			} => stmt.tempfiles,
			_ => false,
		}
	}

	/// Returns any EXPLAIN clause if specified
	pub(crate) fn explain(&self) -> Option<&Explain> {
		match self {
			Statement::Select {
				stmt,
				..
			} => stmt.explain.as_ref(),
			Statement::Update(s) => s.explain.as_ref(),
			Statement::Upsert(s) => s.explain.as_ref(),
			Statement::Delete(s) => s.explain.as_ref(),
			_ => None,
		}
	}

	/// Returns a reference to the appropriate `Permission` field within the
	/// `TableDefinition` structure based on the type of the statement.
	pub(crate) fn permissions<'b>(
		&self,
		table: &'b TableDefinition,
		doc_is_new: bool,
	) -> &'b Permission {
		if self.is_delete() {
			&table.permissions.delete
		} else if self.is_select() {
			&table.permissions.select
		} else if doc_is_new {
			&table.permissions.create
		} else {
			&table.permissions.update
		}
	}

	pub(crate) fn timeout(&self) -> Option<&Expr> {
		match self {
			Statement::Create(s) => Some(&s.timeout),
			Statement::Delete(s) => Some(&s.timeout),
			Statement::Insert(s) => Some(&s.timeout),
			Statement::Select {
				stmt,
				..
			} => Some(&stmt.timeout),
			Statement::Update(s) => Some(&s.timeout),
			Statement::Upsert(s) => Some(&s.timeout),
			_ => None,
		}
	}
	pub(crate) async fn setup_timeout<'a>(
		&self,
		stk: &mut Stk,
		ctx: &'a FrozenContext,
		opt: &Options,
		doc: Option<&CursorDoc>,
	) -> Result<Cow<'a, FrozenContext>> {
		if let Some(t) = self.timeout() {
			let Some(x) = stk
				.run(|stk| t.compute(stk, ctx, opt, doc))
				.await
				.catch_return()?
				.cast_to::<Option<Duration>>()?
			else {
				return Ok(Cow::Borrowed(ctx));
			};
			let mut ctx = Context::new_child(ctx);
			ctx.add_timeout(x.0)?;
			Ok(Cow::Owned(ctx.freeze()))
		} else {
			Ok(Cow::Borrowed(ctx))
		}
	}

	pub(crate) fn setup_query_planner<'a>(
		&self,
		planner: QueryPlanner,
		ctx: Cow<'a, FrozenContext>,
	) -> Cow<'a, FrozenContext> {
		// Add query executors if any
		if planner.has_executors() {
			// Create a new context
			let mut ctx = Context::new_child(&ctx);
			ctx.set_query_planner(planner);
			Cow::Owned(ctx.freeze())
		} else {
			ctx
		}
	}

	pub(crate) async fn from_select<'a>(
		stk: &mut Stk,
		ctx: &FrozenContext,
		opt: &Options,
		doc: Option<&CursorDoc>,
		stmt: &'a SelectStatement,
	) -> Result<Statement<'a>> {
		use crate::expr::visit::MutVisitor;
		use crate::idx::planner::count_exists_rewriter::CountLimitRewriter;

		let omit = exprs_to_fields(stk, ctx, opt, doc, stmt.omit.as_slice()).await?;

		let rewritten_cond = if let Some(cond) = &stmt.cond {
			let mut cond_expr = cond.0.clone();
			if CountLimitRewriter.visit_mut_expr(&mut cond_expr).is_ok() && cond_expr != cond.0 {
				Some(Cond(cond_expr))
			} else {
				None
			}
		} else {
			None
		};

		Ok(Statement::Select {
			stmt,
			omit,
			rewritten_cond,
		})
	}
}