surrealdb-core 3.2.1

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
//! EXPLAIN and EXPLAIN ANALYZE operators.
//!
//! - [`ExplainPlan`] formats a query plan without executing it (read-only).
//! - [`AnalyzePlan`] executes the plan, drains it to completion, then formats the plan tree
//!   together with collected [`OperatorMetrics`].

use std::fmt::Write;
use std::sync::Arc;

use futures::{StreamExt, stream};
use surrealdb_types::ToSql;

use crate::exec::context::{ContextLevel, ExecutionContext};
use crate::exec::{
	AccessMode, CardinalityHint, ExecOperator, FlowResult, OperatorMetrics, ValueBatch,
	ValueBatchStream, buffer_stream,
};
use crate::expr::{ControlFlow, ExplainFormat};
use crate::val::{Array, Object, Value};

/// Number of spaces used per indentation level in text plan output.
const INDENT_WIDTH: usize = 4;

/// EXPLAIN operator - formats an execution plan as text.
///
/// This operator wraps an inner statement's planned content and returns
/// the formatted execution plan as a string value.
#[derive(Debug)]
pub struct ExplainPlan {
	/// The inner statement's planned content
	pub plan: Arc<dyn ExecOperator>,
	/// The output format (currently only Text is supported)
	pub format: ExplainFormat,
}
impl ExecOperator for ExplainPlan {
	fn name(&self) -> &'static str {
		"Explain"
	}

	fn attrs(&self) -> Vec<(String, String)> {
		match self.format {
			ExplainFormat::Text => vec![("format".to_string(), "TEXT".to_string())],
			ExplainFormat::Json => vec![("format".to_string(), "JSON".to_string())],
		}
	}

	fn required_context(&self) -> ContextLevel {
		// EXPLAIN doesn't need database context - it just formats the plan
		ContextLevel::Root
	}

	fn access_mode(&self) -> AccessMode {
		// EXPLAIN is always read-only - it doesn't execute the inner statement
		AccessMode::ReadOnly
	}

	fn cardinality_hint(&self) -> CardinalityHint {
		CardinalityHint::AtMostOne
	}

	fn execute(&self, _ctx: &ExecutionContext) -> FlowResult<ValueBatchStream> {
		let output = match self.format {
			ExplainFormat::Text => {
				let mut plan_text = String::new();
				format_execution_plan(self.plan.as_ref(), &mut plan_text, "");
				Value::String(plan_text.into())
			}
			ExplainFormat::Json => {
				let plan_json = format_execution_plan_json(self.plan.as_ref());
				Value::Object(plan_json)
			}
		};

		Ok(Box::pin(stream::once(async move {
			Ok(ValueBatch {
				values: vec![output],
			})
		})))
	}

	fn is_scalar(&self) -> bool {
		// EXPLAIN returns a single scalar value (text or JSON)
		true
	}
}

// =========================================================================
// EXPLAIN ANALYZE
// =========================================================================

/// EXPLAIN ANALYZE operator - executes the plan, collects metrics, then
/// formats the plan tree with runtime statistics.
///
/// Unlike [`ExplainPlan`], this operator actually executes the inner plan,
/// draining all batches to completion so that every operator's metrics are
/// populated. It then walks the operator tree exactly like `ExplainPlan`
/// but includes elapsed time, row counts, and batch counts.
#[derive(Debug)]
pub struct AnalyzePlan {
	/// The inner statement's planned content
	pub plan: Arc<dyn ExecOperator>,
	/// The output format
	pub format: ExplainFormat,
	/// When true, elapsed durations are omitted from the output, making
	/// it deterministic for test assertions.
	pub redact_volatile_explain_attrs: bool,
}
impl ExecOperator for AnalyzePlan {
	fn name(&self) -> &'static str {
		"ExplainAnalyze"
	}

	fn attrs(&self) -> Vec<(String, String)> {
		match self.format {
			ExplainFormat::Text => vec![("format".to_string(), "TEXT".to_string())],
			ExplainFormat::Json => vec![("format".to_string(), "JSON".to_string())],
		}
	}

	fn required_context(&self) -> ContextLevel {
		// We actually execute the inner plan, so inherit its requirements
		self.plan.required_context()
	}

	fn access_mode(&self) -> AccessMode {
		// We execute the inner plan, so inherit its access mode
		self.plan.access_mode()
	}

	fn cardinality_hint(&self) -> CardinalityHint {
		CardinalityHint::AtMostOne
	}

	fn children(&self) -> Vec<&Arc<dyn ExecOperator>> {
		vec![&self.plan]
	}

	fn execute(&self, ctx: &ExecutionContext) -> FlowResult<ValueBatchStream> {
		// Enable metrics on all operators before execution so that
		// monitor_stream wraps each stream with timing/counting.
		self.plan.enable_metrics();

		// Execute the inner plan to get its stream
		let mut inner_stream = buffer_stream(
			self.plan.execute(ctx)?,
			self.plan.access_mode(),
			self.plan.cardinality_hint(),
			ctx.root().ctx.config.operator_buffer_size,
		);
		let plan = Arc::clone(&self.plan);
		let format = self.format;
		let redact_volatile_explain_attrs = self.redact_volatile_explain_attrs;

		// Create a stream that first drains the inner plan, then formats output
		let analyze_stream = async_stream::try_stream! {
			// Drain all batches from the inner plan so metrics are populated
			let mut total_rows: u64 = 0;
			while let Some(batch_result) = inner_stream.next().await {
				match batch_result {
					Ok(batch) => {
						total_rows += batch.values.len() as u64;
					}
					// Flow control signals mean the inner plan stopped early.
					// Stop draining and format the metrics we've collected so far.
					Err(ControlFlow::Break | ControlFlow::Return(_)) => break,
					// Continue means skip this iteration, keep draining.
					Err(ControlFlow::Continue) => continue,
					// Only actual errors should propagate.
					Err(e @ ControlFlow::Err(_)) => Err(e)?,
				}
			}

			// Now format the plan with metrics
			let output = match format {
				ExplainFormat::Text => {
					let mut plan_text = String::new();
					format_analyze_plan(plan.as_ref(), &mut plan_text, "", redact_volatile_explain_attrs);
					let _ = writeln!(plan_text);
					let _ = write!(plan_text, "Total rows: {}", total_rows);
					Value::String(plan_text.into())
				}
				ExplainFormat::Json => {
					let mut plan_json = format_analyze_plan_json(plan.as_ref(), redact_volatile_explain_attrs);
					plan_json.insert("total_rows", Value::from(total_rows as i64));
					Value::Object(plan_json)
				}
			};

			yield ValueBatch {
				values: vec![output],
			};
		};

		Ok(Box::pin(analyze_stream))
	}

	fn is_scalar(&self) -> bool {
		true
	}
}

// =========================================================================
// Text Formatting
// =========================================================================

/// Format an execution plan node as a text tree
fn format_execution_plan(plan: &dyn ExecOperator, output: &mut String, prefix: &str) {
	// Get operator name and properties
	let name = plan.name();
	let properties = plan.attrs();

	// Show context level
	let context = plan.required_context();
	let _ = write!(output, "{} [ctx: {}]", name, context.short_name());

	// Show properties if any
	if !properties.is_empty() {
		let _ = write!(output, " [");
		for (i, (key, value)) in properties.iter().enumerate() {
			if i > 0 {
				let _ = write!(output, ", ");
			}
			let _ = write!(output, "{key}: {value}");
		}
		let _ = write!(output, "]");
	}

	let _ = writeln!(output);

	// Format expressions that contain embedded operators
	let expressions = plan.expressions();
	for (role, expr) in &expressions {
		let embedded = expr.embedded_operators();
		if !embedded.is_empty() {
			for (embed_role, embed_plan) in &embedded {
				let _ = write!(output, "{}  {}.{}: ", prefix, role, embed_role);
				format_execution_plan(embed_plan.as_ref(), output, &format!("{}  ", prefix));
			}
		}
	}

	// Format children with indentation
	let children = plan.children();
	if !children.is_empty() {
		let child_prefix = format!("{}{:width$}", prefix, "", width = INDENT_WIDTH);
		for child in children.iter() {
			let _ = write!(output, "{}", child_prefix);
			format_execution_plan(child.as_ref(), output, &child_prefix);
		}
	}
}

// =========================================================================
// JSON Formatting
// =========================================================================

/// Format an execution plan node as a JSON object
fn format_execution_plan_json(plan: &dyn ExecOperator) -> Object {
	let mut obj = Object::default();

	obj.insert("operator", Value::String(plan.name().into()));

	obj.insert("context", Value::String(plan.required_context().short_name().into()));

	let attrs = plan.attrs();
	if !attrs.is_empty() {
		let mut attrs_obj = Object::default();
		for (key, value) in attrs {
			attrs_obj.insert(key, Value::String(value.into()));
		}
		obj.insert("attributes", Value::Object(attrs_obj));
	}

	let expressions = plan.expressions();
	if !expressions.is_empty() {
		let exprs_arr: Vec<Value> = expressions
			.iter()
			.map(|(role, expr)| {
				let mut expr_obj = Object::default();
				expr_obj.insert("role", Value::String((*role).into()));
				expr_obj.insert("sql", Value::String(expr.to_sql().into()));

				let embedded = expr.embedded_operators();
				if !embedded.is_empty() {
					let embedded_arr: Vec<Value> = embedded
						.iter()
						.map(|(embed_role, embed_plan)| {
							let mut e = Object::default();
							e.insert("role", Value::String((*embed_role).into()));
							e.insert(
								"plan",
								Value::Object(format_execution_plan_json(embed_plan.as_ref())),
							);
							Value::Object(e)
						})
						.collect();
					expr_obj.insert("embedded_operators", Value::Array(Array::from(embedded_arr)));
				}

				Value::Object(expr_obj)
			})
			.collect();
		obj.insert("expressions", Value::Array(Array::from(exprs_arr)));
	}

	let children = plan.children();
	if !children.is_empty() {
		let children_array: Vec<Value> = children
			.iter()
			.map(|child| Value::Object(format_execution_plan_json(child.as_ref())))
			.collect();
		obj.insert("children", Value::Array(Array::from(children_array)));
	}

	obj
}

// =========================================================================
// ANALYZE Formatters (include metrics)
// =========================================================================

/// Format metrics as a human-readable string fragment.
///
/// When `redact_volatile_explain_attrs` is true, elapsed time and batch counts are
/// omitted so the output is deterministic for test assertions.
fn format_metrics_text(metrics: &OperatorMetrics, redact_volatile_explain_attrs: bool) -> String {
	let rows = metrics.output_rows();

	if redact_volatile_explain_attrs {
		return format!("rows: {}", rows);
	}

	let batches = metrics.output_batches();
	let elapsed = metrics.elapsed_ns();

	// Format elapsed time in the most readable unit
	let elapsed_str = if elapsed >= 1_000_000_000 {
		format!("{:.2}s", elapsed as f64 / 1_000_000_000.0)
	} else if elapsed >= 1_000_000 {
		format!("{:.2}ms", elapsed as f64 / 1_000_000.0)
	} else if elapsed >= 1_000 {
		format!("{:.2}µs", elapsed as f64 / 1_000.0)
	} else {
		format!("{}ns", elapsed)
	};

	// Scan-side counters that depend on how far the scan progressed (volatile
	// like batches/elapsed), rendered only when non-zero. `scanned` is the
	// denominator for graph-traversal filter selectivity (matched = rows);
	// `skipped` is the TopK threshold-pushdown reject count.
	let mut extra = String::new();
	let scanned = metrics.edges_scanned();
	if scanned > 0 {
		extra.push_str(&format!(", scanned: {}", scanned));
	}
	let skipped = metrics.skipped_rows();
	if skipped > 0 {
		extra.push_str(&format!(", skipped: {}", skipped));
	}
	format!("rows: {}, batches: {}, elapsed: {}{}", rows, batches, elapsed_str, extra)
}

/// Format an execution plan node as a text tree with metrics.
fn format_analyze_plan(
	plan: &dyn ExecOperator,
	output: &mut String,
	prefix: &str,
	redact_volatile_explain_attrs: bool,
) {
	let name = plan.name();
	let properties = plan.attrs();

	// Show context level
	let context = plan.required_context();
	let _ = write!(output, "{} [ctx: {}]", name, context.short_name());

	// Show properties if any
	if !properties.is_empty() {
		let _ = write!(output, " [");
		for (i, (key, value)) in properties.iter().enumerate() {
			if i > 0 {
				let _ = write!(output, ", ");
			}
			let _ = write!(output, "{key}: {value}");
		}
		let _ = write!(output, "]");
	}

	// Show metrics if available
	if let Some(metrics) = plan.metrics() {
		let _ =
			write!(output, " {{{}}}", format_metrics_text(metrics, redact_volatile_explain_attrs));
	}

	let _ = writeln!(output);

	// Format expressions with embedded operators (with metrics)
	let expressions = plan.expressions();
	for (role, expr) in &expressions {
		let embedded = expr.embedded_operators();
		if !embedded.is_empty() {
			for (embed_role, embed_plan) in &embedded {
				let _ = write!(output, "{}  {}.{}: ", prefix, role, embed_role);
				format_analyze_plan(
					embed_plan.as_ref(),
					output,
					&format!("{}  ", prefix),
					redact_volatile_explain_attrs,
				);
			}
		}
	}

	// Format children with indentation
	let children = plan.children();
	if !children.is_empty() {
		let child_prefix = format!("{}{:width$}", prefix, "", width = INDENT_WIDTH);
		for child in children.iter() {
			let _ = write!(output, "{}", child_prefix);
			format_analyze_plan(
				child.as_ref(),
				output,
				&child_prefix,
				redact_volatile_explain_attrs,
			);
		}
	}
}

/// Format an execution plan node as a JSON object with metrics.
fn format_analyze_plan_json(
	plan: &dyn ExecOperator,
	redact_volatile_explain_attrs: bool,
) -> Object {
	let mut obj = Object::default();

	obj.insert("operator", Value::String(plan.name().into()));

	obj.insert("context", Value::String(plan.required_context().short_name().into()));

	let attrs = plan.attrs();
	if !attrs.is_empty() {
		let mut attrs_obj = Object::default();
		for (key, value) in attrs {
			attrs_obj.insert(key, Value::String(value.into()));
		}
		obj.insert("attributes", Value::Object(attrs_obj));
	}

	if let Some(metrics) = plan.metrics() {
		let mut metrics_obj = Object::default();
		metrics_obj.insert("output_rows", Value::from(metrics.output_rows() as i64));
		if !redact_volatile_explain_attrs {
			metrics_obj.insert("output_batches", Value::from(metrics.output_batches() as i64));
			metrics_obj.insert("elapsed_ns", Value::from(metrics.elapsed_ns() as i64));
			// Volatile (progress/publish-timing dependent); rendered only when
			// non-zero. `edges_scanned` is the graph-traversal selectivity
			// denominator (matched = output_rows).
			let scanned = metrics.edges_scanned();
			if scanned > 0 {
				metrics_obj.insert("edges_scanned", Value::from(scanned as i64));
			}
			let skipped = metrics.skipped_rows();
			if skipped > 0 {
				metrics_obj.insert("skipped_rows", Value::from(skipped as i64));
			}
		}
		obj.insert("metrics", Value::Object(metrics_obj));
	}

	let expressions = plan.expressions();
	if !expressions.is_empty() {
		let exprs_arr: Vec<Value> = expressions
			.iter()
			.map(|(role, expr)| {
				let mut expr_obj = Object::default();
				expr_obj.insert("role", Value::String((*role).into()));
				expr_obj.insert("sql", Value::String(expr.to_sql().into()));

				let embedded = expr.embedded_operators();
				if !embedded.is_empty() {
					let embedded_arr: Vec<Value> = embedded
						.iter()
						.map(|(embed_role, embed_plan)| {
							let mut e = Object::default();
							e.insert("role", Value::String((*embed_role).into()));
							e.insert(
								"plan",
								Value::Object(format_analyze_plan_json(
									embed_plan.as_ref(),
									redact_volatile_explain_attrs,
								)),
							);
							Value::Object(e)
						})
						.collect();
					expr_obj.insert("embedded_operators", Value::Array(Array::from(embedded_arr)));
				}

				Value::Object(expr_obj)
			})
			.collect();
		obj.insert("expressions", Value::Array(Array::from(exprs_arr)));
	}

	// Add children if any
	let children = plan.children();
	if !children.is_empty() {
		let children_array: Vec<Value> = children
			.iter()
			.map(|child| {
				Value::Object(format_analyze_plan_json(
					child.as_ref(),
					redact_volatile_explain_attrs,
				))
			})
			.collect();
		obj.insert("children", Value::Array(Array::from(children_array)));
	}

	obj
}