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
use anyhow::{Result, bail};
use surrealdb_strand::Strand;

use crate::err::Error;
use crate::expr::tokenizer::Tokenizer as SqlTokenizer;
use crate::idx::ft::Position;
use crate::idx::ft::analyzer::filter::{Filter, FilterResult, Term};
use crate::idx::ft::offset::Offset;
use crate::val::Value;

pub(in crate::idx::ft) struct Tokens {
	/// The input string. Held as a `Strand` so that inline (short) inputs do
	/// not force a heap allocation during FT indexing, and heap (long) inputs
	/// are shared via `Arc<str>` rather than copied.
	i: Strand,
	/// The final list of tokens
	t: Vec<Token>,
}

impl Tokens {
	pub(in crate::idx::ft) fn new(i: Strand) -> Self {
		Self {
			i,
			t: Vec::new(),
		}
	}

	pub(in crate::idx::ft) fn get_token_string<'a>(&'a self, t: &'a Token) -> Result<&'a str> {
		t.get_str(&self.i)
	}

	pub(super) fn filter(self, f: &Filter) -> Result<Tokens> {
		let mut tks = Vec::new();
		for tk in self.t {
			if tk.is_empty() {
				continue;
			}
			let c = tk.get_str(&self.i)?;
			match f.apply_filter(c) {
				FilterResult::Term(t) => match t {
					Term::Unchanged => tks.push(tk),
					Term::NewTerm(t, s) => tks.push(tk.new_token(t, s)),
				},
				FilterResult::Terms(ts) => {
					let mut already_pushed = false;
					for t in ts {
						match t {
							Term::Unchanged => {
								if !already_pushed {
									tks.push(tk.clone());
									already_pushed = true;
								}
							}
							Term::NewTerm(t, s) => tks.push(tk.new_token(t, s)),
						}
					}
				}
				FilterResult::Ignore => {}
			};
		}
		Ok(Tokens {
			i: self.i,
			t: tks,
		})
	}

	pub(in crate::idx::ft) fn list(&self) -> &Vec<Token> {
		&self.t
	}

	pub(in crate::idx::ft) fn try_contains(&self, s: &str) -> Result<bool> {
		for t in &self.t {
			if self.get_token_string(t)?.eq(s) {
				return Ok(true);
			}
		}
		Ok(false)
	}
}

impl TryFrom<Tokens> for Value {
	type Error = anyhow::Error;

	fn try_from(tokens: Tokens) -> Result<Self> {
		let mut vec: Vec<Value> = Vec::with_capacity(tokens.t.len());
		for token in tokens.t {
			vec.push(token.get_str(&tokens.i)?.into())
		}
		Ok(vec.into())
	}
}

#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord, Hash)]
pub(in crate::idx::ft) enum Token {
	Ref {
		chars: (Position, Position, Position),
		bytes: (Position, Position),
		len: u32,
	},
	String {
		chars: (Position, Position, Position),
		bytes: (Position, Position),
		term: String,
		len: u32,
	},
}

impl Token {
	fn new_token(&self, term: String, start: Position) -> Self {
		let len = term.chars().count() as u32;
		match self {
			Token::Ref {
				chars,
				bytes,
				..
			} => Token::String {
				chars: (chars.0, chars.1 + start, chars.2),
				bytes: *bytes,
				term,
				len,
			},
			Token::String {
				chars,
				bytes,
				..
			} => Token::String {
				chars: (chars.0, chars.1 + start, chars.2),
				bytes: *bytes,
				term,
				len,
			},
		}
	}

	pub(in crate::idx::ft) fn new_offset(&self, i: u32) -> Offset {
		match self {
			Token::Ref {
				chars,
				..
			} => Offset::new(i, chars.0, chars.1, chars.2),
			Token::String {
				chars,
				..
			} => Offset::new(i, chars.0, chars.1, chars.2),
		}
	}

	fn is_empty(&self) -> bool {
		match self {
			Token::Ref {
				chars,
				..
			} => chars.0 == chars.2,
			Token::String {
				term,
				..
			} => term.is_empty(),
		}
	}

	pub(in crate::idx::ft) fn get_char_len(&self) -> u32 {
		match self {
			Token::Ref {
				len,
				..
			} => *len,
			Token::String {
				len,
				..
			} => *len,
		}
	}

	pub(super) fn get_str<'a>(&'a self, i: &'a str) -> Result<&'a str> {
		match self {
			Token::Ref {
				bytes,
				..
			} => {
				let s = bytes.0 as usize;
				let e = bytes.1 as usize;
				let l = i.len();
				if s >= l || e > l {
					bail!(Error::AnalyzerError(format!(
						"Unable to extract the token. The offset position ({s},{e}) is out of range ({l})."
					)));
				}
				Ok(&i[s..e])
			}
			Token::String {
				term,
				..
			} => Ok(term),
		}
	}
}

pub(super) struct Tokenizer {
	splitters: Vec<Splitter>,
}

impl Tokenizer {
	pub(in crate::idx::ft) fn new(t: &[SqlTokenizer]) -> Self {
		Self {
			splitters: t.iter().map(|t| t.into()).collect(),
		}
	}

	fn character_role(&mut self, c: char) -> CharacterRole {
		let cl: CharacterClass = c.into();
		// If a character class is not supported, we can safely ignore the character
		if !cl.is_valid() {
			return CharacterRole::NotTokenizable;
		}
		// At this stage, by default, we consider a character being part of the current
		// token
		let mut r = CharacterRole::PartOfCurrentToken;
		for s in &mut self.splitters {
			match s.character_role(cl) {
				// If a tokenizer considers the character being an isolated token we can immediately
				// return
				CharacterRole::IsolatedToken => return CharacterRole::IsolatedToken,
				// The character is part of a new token
				CharacterRole::StartsNewToken => r = CharacterRole::StartsNewToken,
				// If a tokenizer considers the character being not tokenizable we can immediately
				// return
				CharacterRole::NotTokenizable => return CharacterRole::NotTokenizable,
				// We keep the character being part of the current token
				CharacterRole::PartOfCurrentToken => {}
			}
		}
		r
	}

	pub(super) fn tokenize(t: &[SqlTokenizer], i: Strand) -> Tokens {
		let mut w = Tokenizer::new(t);
		let mut last_char_pos = 0;
		let mut last_byte_pos = 0;
		let mut current_char_pos = 0;
		let mut current_byte_pos = 0;
		let mut previous_character_role = CharacterRole::PartOfCurrentToken;
		let mut t = Vec::new();
		for c in i.chars() {
			let char_len = c.len_utf8() as Position;
			let cr = w.character_role(c);
			// if the new character is not part of the current token,
			if !matches!(cr, CharacterRole::PartOfCurrentToken)
				|| matches!(previous_character_role, CharacterRole::IsolatedToken)
			{
				// we add a new token (if there is a pending one)
				if last_char_pos < current_char_pos {
					t.push(Token::Ref {
						chars: (last_char_pos, last_char_pos, current_char_pos),
						bytes: (last_byte_pos, current_byte_pos),
						len: current_char_pos - last_char_pos,
					});
				}
				last_char_pos = current_char_pos;
				last_byte_pos = current_byte_pos;
				// If the character is not valid for indexing (space, control...)
				// Then we increase the last position to the next character
				if matches!(cr, CharacterRole::NotTokenizable) {
					last_char_pos += 1;
					last_byte_pos += char_len;
				}
			}
			previous_character_role = cr;
			current_char_pos += 1;
			current_byte_pos += char_len;
		}
		// Do we have a pending token?
		if current_char_pos != last_char_pos {
			t.push(Token::Ref {
				chars: (last_char_pos, last_char_pos, current_char_pos),
				bytes: (last_byte_pos, current_byte_pos),
				len: current_char_pos - last_char_pos,
			});
		}
		Tokens {
			i,
			t,
		}
	}
}

struct Splitter {
	t: SqlTokenizer,
	state: CharacterClass,
}

/// Define the character class
#[derive(Clone, Copy)]
enum CharacterClass {
	Unknown,
	Whitespace,
	// True if uppercase
	Alphabetic(bool),
	Numeric,
	Punctuation,
	Other,
}

impl From<char> for CharacterClass {
	fn from(c: char) -> Self {
		if c.is_alphabetic() {
			Self::Alphabetic(c.is_uppercase())
		} else if c.is_numeric() {
			Self::Numeric
		} else if c.is_whitespace() {
			Self::Whitespace
		} else if c.is_ascii_punctuation() {
			Self::Punctuation
		} else {
			Self::Other
		}
	}
}

impl CharacterClass {
	/// Te be valid a character is either alphanumeric, punctuation or
	/// whitespace
	fn is_valid(self) -> bool {
		matches!(self, Self::Alphabetic(_) | Self::Numeric | Self::Punctuation | Self::Whitespace)
	}
}

/// Defines the role of a character in the tokenization process
enum CharacterRole {
	/// The character is a token on its own
	IsolatedToken,
	/// The character is the first character of a new token
	StartsNewToken,
	/// The character can't be part of a token and should be ignored
	NotTokenizable,
	/// The character is part of the current token
	PartOfCurrentToken,
}

impl From<&SqlTokenizer> for Splitter {
	fn from(t: &SqlTokenizer) -> Self {
		Self {
			t: *t,
			state: CharacterClass::Unknown,
		}
	}
}

impl Splitter {
	fn character_role(&mut self, cl: CharacterClass) -> CharacterRole {
		match &self.t {
			SqlTokenizer::Blank => self.blank_role(cl),
			SqlTokenizer::Camel => self.camel_role(cl),
			SqlTokenizer::Class => self.class_role(cl),
			SqlTokenizer::Punct => self.punct_role(cl),
		}
	}

	fn blank_role(&self, cl: CharacterClass) -> CharacterRole {
		if matches!(cl, CharacterClass::Whitespace) {
			CharacterRole::NotTokenizable
		} else {
			CharacterRole::PartOfCurrentToken
		}
	}

	fn class_role(&mut self, cl: CharacterClass) -> CharacterRole {
		let r = match (cl, self.state) {
			(CharacterClass::Alphabetic(_), CharacterClass::Alphabetic(_))
			| (CharacterClass::Numeric, CharacterClass::Numeric)
			| (CharacterClass::Punctuation, CharacterClass::Punctuation) => {
				CharacterRole::PartOfCurrentToken
			}
			(CharacterClass::Other, _)
			| (CharacterClass::Whitespace, _)
			| (CharacterClass::Unknown, _) => CharacterRole::NotTokenizable,
			(_, _) => CharacterRole::StartsNewToken,
		};
		self.state = cl;
		r
	}

	fn punct_role(&self, cl: CharacterClass) -> CharacterRole {
		match cl {
			CharacterClass::Whitespace
			| CharacterClass::Alphabetic(_)
			| CharacterClass::Numeric => CharacterRole::PartOfCurrentToken,
			CharacterClass::Punctuation => CharacterRole::IsolatedToken,
			CharacterClass::Other | CharacterClass::Unknown => CharacterRole::NotTokenizable,
		}
	}

	fn camel_role(&mut self, cl: CharacterClass) -> CharacterRole {
		let r = match cl {
			CharacterClass::Alphabetic(next_upper) => {
				if let CharacterClass::Alphabetic(previous_upper) = self.state {
					if next_upper && !previous_upper {
						CharacterRole::StartsNewToken
					} else {
						CharacterRole::PartOfCurrentToken
					}
				} else {
					CharacterRole::StartsNewToken
				}
			}
			CharacterClass::Numeric | CharacterClass::Punctuation => {
				CharacterRole::PartOfCurrentToken
			}
			CharacterClass::Other | CharacterClass::Whitespace | CharacterClass::Unknown => {
				CharacterRole::NotTokenizable
			}
		};
		self.state = cl;
		r
	}
}

#[cfg(test)]
mod tests {
	use crate::idx::ft::analyzer::tests::test_analyzer;

	#[tokio::test]
	async fn test_tokenize_blank_class() {
		test_analyzer(
			"ANALYZER test TOKENIZERS blank,class FILTERS lowercase",
			"Abc12345xYZ DL1809 item123456 978-3-16-148410-0 1HGCM82633A123456",
			&[
				"abc", "12345", "xyz", "dl", "1809", "item", "123456", "978", "-", "3", "-", "16",
				"-", "148410", "-", "0", "1", "hgcm", "82633", "a", "123456",
			],
		)
		.await;
	}

	#[tokio::test]
	async fn test_tokenize_source_code() {
		test_analyzer(
			"ANALYZER test TOKENIZERS blank,class,camel,punct FILTERS lowercase",
			r#"struct MyRectangle {
    // specified by corners
    top_left: Point,
    bottom_right: Point,
}
static LANGUAGE: &str = "Rust";"#,
			&[
				"struct",
				"my",
				"rectangle",
				"{",
				"/",
				"/",
				"specified",
				"by",
				"corners",
				"top",
				"_",
				"left",
				":",
				"point",
				",",
				"bottom",
				"_",
				"right",
				":",
				"point",
				",",
				"}",
				"static",
				"language",
				":",
				"&",
				"str",
				"=",
				"\"",
				"rust",
				"\"",
				";",
			],
		)
		.await;
	}

	#[tokio::test]
	async fn test_tokenize_punct() {
		test_analyzer(
			"ANALYZER test TOKENIZERS punct",
			";anD pAss...leaving Memories-",
			&[";", "anD pAss", ".", ".", ".", "leaving Memories", "-"],
		)
		.await;
	}
}