surrealdb_core/sql/
thing.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
use super::id::range::IdRange;
use super::{Cond, Expression, Ident, Idiom, Operator, Part, Table};
use crate::ctx::Context;
use crate::dbs::Options;
use crate::doc::CursorDoc;
use crate::err::Error;
use crate::sql::{escape::escape_rid, id::Id, Strand, Value};
use crate::syn;
use derive::Store;
use reblessive::tree::Stk;
use revision::revisioned;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::ops::Bound;
use std::str::FromStr;

const ID: &str = "id";
pub(crate) const TOKEN: &str = "$surrealdb::private::sql::Thing";

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[serde(rename = "$surrealdb::private::sql::Thing")]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct Thing {
	/// Table name
	pub tb: String,
	pub id: Id,
}

impl Thing {
	/// Convert `Thing` to `Cond`
	pub fn to_cond(self) -> Option<Cond> {
		match &self.id {
			Id::Range(r) => match (&r.beg, &r.end) {
				(Bound::Unbounded, Bound::Unbounded) => None,
				(Bound::Unbounded, Bound::Excluded(id)) => {
					Some(Cond(Value::Expression(Box::new(Expression::new(
						Idiom(vec![Part::from(Ident(ID.to_owned()))]).into(),
						Operator::LessThan,
						Thing::from((self.tb, id.to_owned())).into(),
					)))))
				}
				(Bound::Unbounded, Bound::Included(id)) => {
					Some(Cond(Value::Expression(Box::new(Expression::new(
						Idiom(vec![Part::from(Ident(ID.to_owned()))]).into(),
						Operator::LessThanOrEqual,
						Thing::from((self.tb, id.to_owned())).into(),
					)))))
				}
				(Bound::Excluded(id), Bound::Unbounded) => {
					Some(Cond(Value::Expression(Box::new(Expression::new(
						Idiom(vec![Part::from(Ident(ID.to_owned()))]).into(),
						Operator::MoreThan,
						Thing::from((self.tb, id.to_owned())).into(),
					)))))
				}
				(Bound::Included(id), Bound::Unbounded) => {
					Some(Cond(Value::Expression(Box::new(Expression::new(
						Idiom(vec![Part::from(Ident(ID.to_owned()))]).into(),
						Operator::MoreThanOrEqual,
						Thing::from((self.tb, id.to_owned())).into(),
					)))))
				}
				(Bound::Included(lid), Bound::Included(rid)) => {
					Some(Cond(Value::Expression(Box::new(Expression::new(
						Value::Expression(Box::new(Expression::new(
							Idiom(vec![Part::from(Ident(ID.to_owned()))]).into(),
							Operator::MoreThanOrEqual,
							Thing::from((self.tb.clone(), lid.to_owned())).into(),
						))),
						Operator::And,
						Value::Expression(Box::new(Expression::new(
							Idiom(vec![Part::from(Ident(ID.to_owned()))]).into(),
							Operator::LessThanOrEqual,
							Thing::from((self.tb, rid.to_owned())).into(),
						))),
					)))))
				}
				(Bound::Included(lid), Bound::Excluded(rid)) => {
					Some(Cond(Value::Expression(Box::new(Expression::new(
						Value::Expression(Box::new(Expression::new(
							Idiom(vec![Part::from(Ident(ID.to_owned()))]).into(),
							Operator::MoreThanOrEqual,
							Thing::from((self.tb.clone(), lid.to_owned())).into(),
						))),
						Operator::And,
						Value::Expression(Box::new(Expression::new(
							Idiom(vec![Part::from(Ident(ID.to_owned()))]).into(),
							Operator::LessThan,
							Thing::from((self.tb, rid.to_owned())).into(),
						))),
					)))))
				}
				(Bound::Excluded(lid), Bound::Included(rid)) => {
					Some(Cond(Value::Expression(Box::new(Expression::new(
						Value::Expression(Box::new(Expression::new(
							Idiom(vec![Part::from(Ident(ID.to_owned()))]).into(),
							Operator::MoreThan,
							Thing::from((self.tb.clone(), lid.to_owned())).into(),
						))),
						Operator::And,
						Value::Expression(Box::new(Expression::new(
							Idiom(vec![Part::from(Ident(ID.to_owned()))]).into(),
							Operator::LessThanOrEqual,
							Thing::from((self.tb, rid.to_owned())).into(),
						))),
					)))))
				}
				(Bound::Excluded(lid), Bound::Excluded(rid)) => {
					Some(Cond(Value::Expression(Box::new(Expression::new(
						Value::Expression(Box::new(Expression::new(
							Idiom(vec![Part::from(Ident(ID.to_owned()))]).into(),
							Operator::MoreThan,
							Thing::from((self.tb.clone(), lid.to_owned())).into(),
						))),
						Operator::And,
						Value::Expression(Box::new(Expression::new(
							Idiom(vec![Part::from(Ident(ID.to_owned()))]).into(),
							Operator::LessThan,
							Thing::from((self.tb, rid.to_owned())).into(),
						))),
					)))))
				}
			},
			_ => Some(Cond(Value::Expression(Box::new(Expression::new(
				Idiom(vec![Part::from(Ident(ID.to_owned()))]).into(),
				Operator::Equal,
				Thing::from((self.tb, self.id)).into(),
			))))),
		}
	}
}

impl From<(&str, Id)> for Thing {
	fn from((tb, id): (&str, Id)) -> Self {
		Self {
			tb: tb.to_owned(),
			id,
		}
	}
}

impl From<(String, Id)> for Thing {
	fn from((tb, id): (String, Id)) -> Self {
		Self {
			tb,
			id,
		}
	}
}

impl From<(&str, IdRange)> for Thing {
	fn from((tb, id): (&str, IdRange)) -> Self {
		Self {
			tb: tb.to_owned(),
			id: id.into(),
		}
	}
}

impl From<(String, IdRange)> for Thing {
	fn from((tb, id): (String, IdRange)) -> Self {
		Self {
			tb,
			id: id.into(),
		}
	}
}

impl From<(String, String)> for Thing {
	fn from((tb, id): (String, String)) -> Self {
		Self::from((tb, Id::from(id)))
	}
}

impl From<(&str, &str)> for Thing {
	fn from((tb, id): (&str, &str)) -> Self {
		Self::from((tb.to_owned(), Id::from(id)))
	}
}

impl FromStr for Thing {
	type Err = ();
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Self::try_from(s)
	}
}

impl TryFrom<String> for Thing {
	type Error = ();
	fn try_from(v: String) -> Result<Self, Self::Error> {
		Self::try_from(v.as_str())
	}
}

impl TryFrom<Strand> for Thing {
	type Error = ();
	fn try_from(v: Strand) -> Result<Self, Self::Error> {
		Self::try_from(v.as_str())
	}
}

impl TryFrom<&str> for Thing {
	type Error = ();
	fn try_from(v: &str) -> Result<Self, Self::Error> {
		match syn::thing_with_range(v) {
			Ok(v) => Ok(v),
			_ => Err(()),
		}
	}
}

impl Thing {
	/// Convert the Thing to a raw String
	pub fn to_raw(&self) -> String {
		self.to_string()
	}
	/// Check if this Thing is a range
	pub fn is_range(&self) -> bool {
		matches!(self.id, Id::Range(_))
	}
	/// Check if this Thing is of a certain table type
	pub fn is_record_type(&self, types: &[Table]) -> bool {
		types.is_empty() || types.iter().any(|tb| tb.0 == self.tb)
	}
}

impl fmt::Display for Thing {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		write!(f, "{}:{}", escape_rid(&self.tb), self.id)
	}
}

impl Thing {
	/// Process this type returning a computed simple Value
	pub(crate) async fn compute(
		&self,
		stk: &mut Stk,
		ctx: &Context,
		opt: &Options,
		doc: Option<&CursorDoc>,
	) -> Result<Value, Error> {
		Ok(Value::Thing(Thing {
			tb: self.tb.clone(),
			id: self.id.compute(stk, ctx, opt, doc).await?,
		}))
	}
}

#[cfg(test)]
mod test {
	use std::{ops::Bound, str::FromStr};

	use crate::sql::{Array, Id, IdRange, Object, Value};

	use super::Thing;

	#[test]
	fn from() {
		{
			let string = "foo:bar";
			let thing = Thing {
				tb: "foo".into(),
				id: Id::String("bar".into()),
			};
			assert_eq!(thing, Thing::from_str(string).unwrap());
		}
		{
			let string = "foo:1";
			let thing = Thing {
				tb: "foo".into(),
				id: Id::Number(1),
			};
			assert_eq!(thing, Thing::from_str(string).unwrap());
		}
		{
			let string = "foo:[1, 'bar']";
			let thing = Thing {
				tb: "foo".into(),
				id: Id::Array(Array(vec![1i64.into(), "bar".into()])),
			};
			assert_eq!(thing, Thing::from_str(string).unwrap());
		}
		{
			let string = "foo:{bar: 1}";
			let thing = Thing {
				tb: "foo".into(),
				id: Id::Object(Object([("bar".to_string(), Value::from(1))].into_iter().collect())),
			};
			assert_eq!(thing, Thing::from_str(string).unwrap());
		}
		{
			let string = "foo:1..=2";
			let thing = Thing {
				tb: "foo".into(),
				id: Id::Range(Box::new(
					IdRange::try_from((
						Bound::Included(Id::Number(1)),
						Bound::Included(Id::Number(2)),
					))
					.unwrap(),
				)),
			};
			assert_eq!(thing, Thing::from_str(string).unwrap());
		}
	}
}