surrealdb-core 3.2.0

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
use std::fmt;

use anyhow::Result;
use async_channel::Sender;
use surrealdb_types::{SurrealValue, ToSql};

use super::{KVValue, Transaction};
use crate::catalog::providers::{
	ApiProvider, AuthorisationProvider, BucketProvider, DatabaseProvider, TableProvider,
	UserProvider,
};
use crate::catalog::{DatabaseId, NamespaceId, Record, TableDefinition};
use crate::err::Error;
use crate::expr::paths::{IN, OUT};
use crate::expr::statements::define::{DefineAccessStatement, DefineUserStatement};
use crate::expr::{Base, DefineAnalyzerStatement};
use crate::key::record;
use crate::sql::statements::OptionStatement;

#[derive(Clone, Debug, SurrealValue)]
#[surreal(crate = "surrealdb_types")]
#[surreal(default)]
pub struct Config {
	pub users: bool,
	pub accesses: bool,
	pub params: bool,
	pub functions: bool,
	pub analyzers: bool,
	pub apis: bool,
	pub buckets: bool,
	pub modules: bool,
	pub configs: bool,
	pub tables: TableConfig,
	pub versions: bool,
	pub records: bool,
	pub sequences: bool,
}

impl Default for Config {
	fn default() -> Config {
		Config {
			users: true,
			accesses: true,
			params: true,
			functions: true,
			analyzers: true,
			apis: true,
			buckets: true,
			modules: true,
			configs: true,
			tables: TableConfig::default(),
			versions: false,
			records: true,
			sequences: true,
		}
	}
}

/// Named-field wrapper so that the untagged `SurrealValue` serialization
/// can differentiate `Exclude` from `Some` (include).
#[derive(Clone, Debug, SurrealValue)]
#[surreal(crate = "surrealdb_types")]
pub struct ExcludedTables {
	pub exclude: Vec<String>,
}

#[derive(Clone, Debug, Default, SurrealValue)]
#[surreal(crate = "surrealdb_types")]
#[surreal(untagged)]
pub enum TableConfig {
	#[default]
	#[surreal(value = true)]
	All,
	#[surreal(value = false)]
	None,
	Some(Vec<String>),
	Exclude(ExcludedTables),
}

// `From<bool>` exists so the SDK's `ExportBuilder::tables(impl Into<TableConfig>)`
// accepts `tables(true)` / `tables(false)` directly. The semantics are
// documented at the call site (`surrealdb/src/method/export.rs::tables`):
// `true` selects all tables, `false` selects none.
impl From<bool> for TableConfig {
	fn from(value: bool) -> Self {
		match value {
			true => TableConfig::All,
			false => TableConfig::None,
		}
	}
}

impl From<Vec<String>> for TableConfig {
	fn from(value: Vec<String>) -> Self {
		TableConfig::Some(value)
	}
}

impl From<Vec<&str>> for TableConfig {
	fn from(value: Vec<&str>) -> Self {
		TableConfig::Some(value.into_iter().map(ToOwned::to_owned).collect())
	}
}

impl TableConfig {
	/// Check if we should export tables
	pub(crate) fn is_any(&self) -> bool {
		matches!(self, Self::All | Self::Some(_) | Self::Exclude(_))
	}
	// Check if we should export a specific table
	pub(crate) fn includes(&self, table: &str) -> bool {
		match self {
			Self::All => true,
			Self::None => false,
			Self::Some(v) => v.iter().any(|v| v.eq(table)),
			Self::Exclude(v) => !v.exclude.iter().any(|v| v.eq(table)),
		}
	}
	/// Returns the explicitly listed table names, if any.
	pub(crate) fn names(&self) -> Option<&[String]> {
		match self {
			Self::Some(v) => Some(v.as_slice()),
			Self::Exclude(v) => Some(v.exclude.as_slice()),
			_ => None,
		}
	}
}

struct InlineCommentWriter<'a, F>(&'a mut F);
impl<F: fmt::Write> fmt::Write for InlineCommentWriter<'_, F> {
	fn write_str(&mut self, s: &str) -> fmt::Result {
		for c in s.chars() {
			self.write_char(c)?
		}
		Ok(())
	}

	fn write_char(&mut self, c: char) -> fmt::Result {
		match c {
			'\n' => self.0.write_str("\\n"),
			'\r' => self.0.write_str("\\r"),
			// NEL/Next Line
			'\u{0085}' => self.0.write_str("\\u{0085}"),
			// line separator
			'\u{2028}' => self.0.write_str("\\u{2028}"),
			// Paragraph separator
			'\u{2029}' => self.0.write_str("\\u{2029}"),
			_ => self.0.write_char(c),
		}
	}
}

struct InlineCommentDisplay<F>(F);
impl<F: fmt::Display> fmt::Display for InlineCommentDisplay<F> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		fmt::Write::write_fmt(&mut InlineCommentWriter(f), format_args!("{}", self.0))
	}
}

impl Transaction {
	/// Writes the full database contents as binary SQL.
	pub async fn export(
		&self,
		ns: &str,
		db: &str,
		cfg: Config,
		batch_size: u32,
		chn: Sender<Vec<u8>>,
	) -> Result<()> {
		let db = self.get_db_by_name(ns, db, None).await?.ok_or_else(|| {
			anyhow::Error::new(Error::DbNotFound {
				name: db.to_owned(),
			})
		})?;

		// Output USERS, ACCESSES, PARAMS, FUNCTIONS, ANALYZERS
		self.export_metadata(&cfg, &chn, db.namespace_id, db.database_id).await?;
		// Output TABLES
		self.export_tables(&cfg, &chn, db.namespace_id, db.database_id, batch_size).await?;
		Ok(())
	}

	async fn export_metadata(
		&self,
		cfg: &Config,
		chn: &Sender<Vec<u8>>,
		ns: NamespaceId,
		db: DatabaseId,
	) -> Result<()> {
		// Output OPTIONS
		self.export_section("OPTION", [OptionStatement::import()].into_iter(), chn).await?;

		// Output USERS
		if cfg.users {
			let users = self.all_db_users(ns, db, None).await?;
			self.export_section(
				"USERS",
				users.iter().map(|x| DefineUserStatement::from_definition(Base::Db, x)),
				chn,
			)
			.await?;
		}

		// Output ACCESSES
		if cfg.accesses {
			let accesses = self.all_db_accesses(ns, db, None).await?;
			self.export_section(
				"ACCESSES",
				accesses
					.iter()
					.map(|x| DefineAccessStatement::from_definition(Base::Db, x).redact()),
				chn,
			)
			.await?;
		}

		// Output PARAMS
		if cfg.params {
			let params = self.all_db_params(ns, db, None).await?;
			self.export_section("PARAMS", params.iter(), chn).await?;
		}

		// Output FUNCTIONS
		if cfg.functions {
			let functions = self.all_db_functions(ns, db, None).await?;
			self.export_section("FUNCTIONS", functions.iter(), chn).await?;
		}

		// Output ANALYZERS
		if cfg.analyzers {
			let analyzers = self.all_db_analyzers(ns, db, None).await?;
			self.export_section(
				"ANALYZERS",
				analyzers.iter().map(DefineAnalyzerStatement::from_definition),
				chn,
			)
			.await?;
		}

		// Output APIS
		if cfg.apis {
			let apis = self.all_db_apis(ns, db, None).await?;
			self.export_section("APIS", apis.iter(), chn).await?;
		}

		// Output BUCKETS
		if cfg.buckets {
			let buckets = self.all_db_buckets(ns, db, None).await?;
			self.export_section("BUCKETS", buckets.iter(), chn).await?;
		}

		// Output MODULES
		if cfg.modules {
			let modules = self.all_db_modules(ns, db, None).await?;
			self.export_section("MODULES", modules.iter(), chn).await?;
		}

		// Output CONFIGS
		if cfg.configs {
			let configs = self.all_db_configs(ns, db, None).await?;
			self.export_section("CONFIGS", configs.iter(), chn).await?;
		}

		// Output SEQUENCES
		if cfg.sequences {
			let sequences = self.all_db_sequences(ns, db, None).await?;
			self.export_section("SEQUENCES", sequences.iter(), chn).await?;
		}

		Ok(())
	}

	async fn export_section<T>(
		&self,
		title: &str,
		items: impl ExactSizeIterator<Item = T>,
		chn: &Sender<Vec<u8>>,
	) -> Result<()>
	where
		T: ToSql,
	{
		if items.len() == 0 {
			return Ok(());
		}

		chn.send(bytes!("-- ------------------------------")).await?;
		chn.send(bytes!(format!("-- {}", InlineCommentDisplay(title)))).await?;
		chn.send(bytes!("-- ------------------------------")).await?;
		chn.send(bytes!("")).await?;

		for item in items {
			chn.send(bytes!(format!("{};", item.to_sql()))).await?;
		}

		chn.send(bytes!("")).await?;
		Ok(())
	}

	async fn export_tables(
		&self,
		cfg: &Config,
		chn: &Sender<Vec<u8>>,
		ns: NamespaceId,
		db: DatabaseId,
		batch_size: u32,
	) -> Result<()> {
		// Check if tables are included in the export config
		if !cfg.tables.is_any() {
			return Ok(());
		}
		// Fetch all of the tables for this NS / DB
		let tables = self.all_tb(ns, db, None).await?;
		// Warn if any specified table names don't match existing tables
		if let Some(names) = cfg.tables.names() {
			let existing: Vec<&str> = tables.iter().map(|t| t.name.as_str()).collect();
			for name in names {
				if !existing.contains(&name.as_str()) {
					warn!("Table '{name}' does not exist in the database");
				}
			}
		}
		// Loop over all of the tables in order
		for table in tables.iter() {
			// Check if this table is included in the export config
			if !cfg.tables.includes(&table.name) {
				continue;
			}
			// Export the table definition structure first
			self.export_table_structure(ns, db, table, chn).await?;
			// Then export the table data if its desired
			if cfg.records {
				self.export_table_data(ns, db, table, chn, batch_size).await?;
			}
		}

		Ok(())
	}

	async fn export_table_structure(
		&self,
		ns: NamespaceId,
		db: DatabaseId,
		table: &TableDefinition,
		chn: &Sender<Vec<u8>>,
	) -> Result<()> {
		chn.send(bytes!("-- ------------------------------")).await?;
		chn.send(bytes!(format!("-- TABLE: {}", InlineCommentDisplay(&table.name)))).await?;
		chn.send(bytes!("-- ------------------------------")).await?;
		chn.send(bytes!("")).await?;
		chn.send(bytes!(format!("{};", table.to_sql()))).await?;
		chn.send(bytes!("")).await?;
		// Export all table field definitions with OVERWRITE to ensure
		// idempotent re-import (relation tables auto-generate in/out fields,
		// and array types generate sub-field definitions that would conflict).
		let fields = self.all_tb_fields(ns, db, &table.name, None).await?;
		for field in fields.iter() {
			let mut stmt = field.to_sql_definition();
			stmt.kind = crate::sql::statements::define::DefineKind::Overwrite;
			chn.send(bytes!(format!("{};", stmt.to_sql()))).await?;
		}
		chn.send(bytes!("")).await?;
		// Export all table index definitions for this table
		let indexes = self.all_tb_indexes(ns, db, &table.name, None).await?;
		for index in indexes.iter() {
			chn.send(bytes!(format!("{};", index.to_sql()))).await?;
		}
		chn.send(bytes!("")).await?;
		// Export all table event definitions for this table
		let events = self.all_tb_events(ns, db, &table.name, None).await?;
		for event in events.iter() {
			chn.send(bytes!(format!("{};", event.to_sql()))).await?;
		}
		chn.send(bytes!("")).await?;
		// Everything ok
		Ok(())
	}

	async fn export_table_data(
		&self,
		ns: NamespaceId,
		db: DatabaseId,
		table: &TableDefinition,
		chn: &Sender<Vec<u8>>,
		batch_size: u32,
	) -> Result<()> {
		chn.send(bytes!("-- ------------------------------")).await?;
		chn.send(bytes!(format!("-- TABLE DATA: {}", InlineCommentDisplay(&table.name)))).await?;
		chn.send(bytes!("-- ------------------------------")).await?;
		chn.send(bytes!("")).await?;

		let beg = crate::key::record::prefix(ns, db, &table.name)?;
		let end = crate::key::record::suffix(ns, db, &table.name)?;
		let mut next = Some(beg..end);

		while let Some(rng) = next {
			let batch = self.batch_keys_vals(rng, batch_size, None).await?;
			next = batch.next;
			// If there are no values, return early.
			if batch.result.is_empty() {
				break;
			}
			self.export_regular_data(batch.result, chn).await?;
		}

		chn.send(bytes!("")).await?;
		Ok(())
	}

	/// Processes a record and categorizes it for SQL export.
	///
	/// This function processes a record, categorizing it into either normal
	/// records or graph edge records, and writes it to the appropriate string
	/// buffer for later SQL generation.
	///
	/// Note: Only the latest version of each record is exported. Historical
	/// versions must be exported at the KV level.
	///
	/// # Arguments
	///
	/// * `record` - The record to be processed. The `id` field must already be present in `data`
	///   (this is the case when the record was produced by [`Record::kv_decode_value_with_id`]).
	/// * `records_relate` - A mutable reference to a string buffer for graph edge records.
	/// * `records_normal` - A mutable reference to a string buffer for normal records.
	fn process_record(record: &Record, records_relate: &mut String, records_normal: &mut String) {
		// Match on the value to determine if it is a graph edge record or a normal record.
		if record.is_edge()
			&& let crate::val::Value::RecordId(_) = record.data.pick(&IN)
			&& let crate::val::Value::RecordId(_) = record.data.pick(&OUT)
		{
			// If the value is a graph edge record (indicated by EDGE, IN, and OUT fields):
			// Write the value to the records_relate string.
			if !records_relate.is_empty() {
				records_relate.push_str(", ");
			}
			records_relate.push_str(&record.data.to_sql());
		} else {
			// If the value is a normal record, write it to the records_normal string.
			if !records_normal.is_empty() {
				records_normal.push_str(", ");
			}
			records_normal.push_str(&record.data.to_sql());
		}
	}

	/// Exports regular data to the provided channel.
	///
	/// This function processes a list of regular values, converting them into
	/// SQL commands and sending them to the provided channel. It handles both
	/// normal records and graph edge records, and ensures that the appropriate
	/// SQL commands are generated for each type of record.
	///
	/// # Arguments
	///
	/// * `regular_values` - A vector of tuples containing the regular values to be exported. Each
	///   tuple consists of a key and a value.
	/// * `chn` - A reference to the channel to which the SQL commands will be sent.
	///
	/// # Returns
	///
	/// * `Result<()>` - Returns `Ok(())` if the operation is successful, or an `Error` if an error
	///   occurs.
	async fn export_regular_data(
		&self,
		regular_values: Vec<(Vec<u8>, Vec<u8>)>,
		chn: &Sender<Vec<u8>>,
	) -> Result<()> {
		// Initialize strings to hold normal records and graph edge records.
		// Write directly to strings to avoid unnecessary allocations.
		let mut records_normal = String::new();
		let mut records_relate = String::new();

		// Process each regular value.
		for (k, v) in regular_values {
			let k = record::RecordKey::decode_key(&k)?;
			let rid = crate::val::RecordId {
				table: k.tb.into_owned(),
				key: k.id,
			};
			let v = Record::kv_decode_value(&v, rid)?;
			// Process the value and categorize it into records_relate or records_normal.
			Self::process_record(&v, &mut records_relate, &mut records_normal);
		}

		// If there are normal records, generate and send the INSERT SQL command.
		if !records_normal.is_empty() {
			let sql = format!("INSERT [ {} ];", records_normal);
			chn.send(bytes!(sql)).await?;
		}

		// If there are graph edge records, generate and send the INSERT RELATION SQL
		// command.
		if !records_relate.is_empty() {
			let sql = format!("INSERT RELATION [ {} ];", records_relate);
			chn.send(bytes!(sql)).await?;
		}

		Ok(())
	}
}