surrealdb/sql/
array.rs

1use crate::ctx::Context;
2use crate::dbs::{Options, Transaction};
3use crate::doc::CursorDoc;
4use crate::err::Error;
5use crate::sql::{
6	fmt::{pretty_indent, Fmt, Pretty},
7	Number, Operation, Value,
8};
9use revision::revisioned;
10use serde::{Deserialize, Serialize};
11use std::collections::HashSet;
12use std::fmt::{self, Display, Formatter, Write};
13use std::ops;
14use std::ops::Deref;
15use std::ops::DerefMut;
16
17pub(crate) const TOKEN: &str = "$surrealdb::private::sql::Array";
18
19#[derive(Clone, Debug, Default, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize, Hash)]
20#[serde(rename = "$surrealdb::private::sql::Array")]
21#[revisioned(revision = 1)]
22pub struct Array(pub Vec<Value>);
23
24impl From<Value> for Array {
25	fn from(v: Value) -> Self {
26		vec![v].into()
27	}
28}
29
30impl From<Vec<Value>> for Array {
31	fn from(v: Vec<Value>) -> Self {
32		Self(v)
33	}
34}
35
36impl From<Vec<i32>> for Array {
37	fn from(v: Vec<i32>) -> Self {
38		Self(v.into_iter().map(Value::from).collect())
39	}
40}
41
42impl From<Vec<f64>> for Array {
43	fn from(v: Vec<f64>) -> Self {
44		Self(v.into_iter().map(Value::from).collect())
45	}
46}
47
48impl From<Vec<&str>> for Array {
49	fn from(v: Vec<&str>) -> Self {
50		Self(v.into_iter().map(Value::from).collect())
51	}
52}
53
54impl From<Vec<String>> for Array {
55	fn from(v: Vec<String>) -> Self {
56		Self(v.into_iter().map(Value::from).collect())
57	}
58}
59
60impl From<Vec<Number>> for Array {
61	fn from(v: Vec<Number>) -> Self {
62		Self(v.into_iter().map(Value::from).collect())
63	}
64}
65
66impl From<Vec<Operation>> for Array {
67	fn from(v: Vec<Operation>) -> Self {
68		Self(v.into_iter().map(Value::from).collect())
69	}
70}
71
72impl From<Vec<bool>> for Array {
73	fn from(v: Vec<bool>) -> Self {
74		Self(v.into_iter().map(Value::from).collect())
75	}
76}
77
78impl From<Array> for Vec<Value> {
79	fn from(s: Array) -> Self {
80		s.0
81	}
82}
83
84impl FromIterator<Value> for Array {
85	fn from_iter<I: IntoIterator<Item = Value>>(iter: I) -> Self {
86		Array(iter.into_iter().collect())
87	}
88}
89
90impl Deref for Array {
91	type Target = Vec<Value>;
92	fn deref(&self) -> &Self::Target {
93		&self.0
94	}
95}
96
97impl DerefMut for Array {
98	fn deref_mut(&mut self) -> &mut Self::Target {
99		&mut self.0
100	}
101}
102
103impl IntoIterator for Array {
104	type Item = Value;
105	type IntoIter = std::vec::IntoIter<Self::Item>;
106	fn into_iter(self) -> Self::IntoIter {
107		self.0.into_iter()
108	}
109}
110
111impl Array {
112	// Create a new empty array
113	pub fn new() -> Self {
114		Self::default()
115	}
116	// Create a new array with capacity
117	pub fn with_capacity(len: usize) -> Self {
118		Self(Vec::with_capacity(len))
119	}
120	// Get the length of the array
121	pub fn len(&self) -> usize {
122		self.0.len()
123	}
124	// Check if there array is empty
125	pub fn is_empty(&self) -> bool {
126		self.0.is_empty()
127	}
128}
129
130impl Array {
131	/// Process this type returning a computed simple Value
132	pub(crate) async fn compute(
133		&self,
134		ctx: &Context<'_>,
135		opt: &Options,
136		txn: &Transaction,
137		doc: Option<&CursorDoc<'_>>,
138	) -> Result<Value, Error> {
139		let mut x = Self::with_capacity(self.len());
140		for v in self.iter() {
141			match v.compute(ctx, opt, txn, doc).await {
142				Ok(v) => x.push(v),
143				Err(e) => return Err(e),
144			};
145		}
146		Ok(Value::Array(x))
147	}
148
149	pub(crate) fn is_all_none_or_null(&self) -> bool {
150		self.0.iter().all(|v| v.is_none_or_null())
151	}
152}
153
154impl Display for Array {
155	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
156		let mut f = Pretty::from(f);
157		f.write_char('[')?;
158		if !self.is_empty() {
159			let indent = pretty_indent();
160			write!(f, "{}", Fmt::pretty_comma_separated(self.as_slice()))?;
161			drop(indent);
162		}
163		f.write_char(']')
164	}
165}
166
167// ------------------------------
168
169impl ops::Add<Value> for Array {
170	type Output = Self;
171	fn add(mut self, other: Value) -> Self {
172		self.0.push(other);
173		self
174	}
175}
176
177impl ops::Add for Array {
178	type Output = Self;
179	fn add(mut self, mut other: Self) -> Self {
180		self.0.append(&mut other.0);
181		self
182	}
183}
184
185// ------------------------------
186
187impl ops::Sub<Value> for Array {
188	type Output = Self;
189	fn sub(mut self, other: Value) -> Self {
190		if let Some(p) = self.0.iter().position(|x| *x == other) {
191			self.0.remove(p);
192		}
193		self
194	}
195}
196
197impl ops::Sub for Array {
198	type Output = Self;
199	fn sub(mut self, other: Self) -> Self {
200		for v in other.0 {
201			if let Some(p) = self.0.iter().position(|x| *x == v) {
202				self.0.remove(p);
203			}
204		}
205		self
206	}
207}
208
209// ------------------------------
210
211pub trait Abolish<T> {
212	fn abolish<F>(&mut self, f: F)
213	where
214		F: FnMut(usize) -> bool;
215}
216
217impl<T> Abolish<T> for Vec<T> {
218	fn abolish<F>(&mut self, mut f: F)
219	where
220		F: FnMut(usize) -> bool,
221	{
222		let mut i = 0;
223		// FIXME: use drain_filter once stabilized (https://github.com/rust-lang/rust/issues/43244)
224		// to avoid negation of the predicate return value.
225		self.retain(|_| {
226			let retain = !f(i);
227			i += 1;
228			retain
229		});
230	}
231}
232
233// ------------------------------
234
235pub(crate) trait Clump<T> {
236	fn clump(self, clump_size: usize) -> T;
237}
238
239impl Clump<Array> for Array {
240	fn clump(self, clump_size: usize) -> Array {
241		self.0
242			.chunks(clump_size)
243			.map::<Value, _>(|chunk| chunk.to_vec().into())
244			.collect::<Vec<_>>()
245			.into()
246	}
247}
248
249// ------------------------------
250
251pub(crate) trait Combine<T> {
252	fn combine(self, other: T) -> T;
253}
254
255impl Combine<Array> for Array {
256	fn combine(self, other: Self) -> Array {
257		let mut out = Self::with_capacity(self.len().saturating_mul(other.len()));
258		for a in self.iter() {
259			for b in other.iter() {
260				out.push(vec![a.clone(), b.clone()].into());
261			}
262		}
263		out
264	}
265}
266
267// ------------------------------
268
269pub(crate) trait Complement<T> {
270	fn complement(self, other: T) -> T;
271}
272
273impl Complement<Array> for Array {
274	fn complement(self, other: Self) -> Array {
275		let mut out = Array::new();
276		for v in self.into_iter() {
277			if !other.contains(&v) {
278				out.push(v)
279			}
280		}
281		out
282	}
283}
284
285// ------------------------------
286
287pub(crate) trait Concat<T> {
288	fn concat(self, other: T) -> T;
289}
290
291impl Concat<Array> for Array {
292	fn concat(mut self, mut other: Array) -> Array {
293		self.append(&mut other);
294		self
295	}
296}
297
298// ------------------------------
299
300pub(crate) trait Difference<T> {
301	fn difference(self, other: T) -> T;
302}
303
304impl Difference<Array> for Array {
305	fn difference(self, mut other: Array) -> Array {
306		let mut out = Array::new();
307		for v in self.into_iter() {
308			if let Some(pos) = other.iter().position(|w| v == *w) {
309				other.remove(pos);
310			} else {
311				out.push(v);
312			}
313		}
314		out.append(&mut other);
315		out
316	}
317}
318
319// ------------------------------
320
321pub(crate) trait Flatten<T> {
322	fn flatten(self) -> T;
323}
324
325impl Flatten<Array> for Array {
326	fn flatten(self) -> Array {
327		let mut out = Array::new();
328		for v in self.into_iter() {
329			match v {
330				Value::Array(mut a) => out.append(&mut a),
331				_ => out.push(v),
332			}
333		}
334		out
335	}
336}
337
338// ------------------------------
339
340pub(crate) trait Intersect<T> {
341	fn intersect(self, other: T) -> T;
342}
343
344impl Intersect<Self> for Array {
345	fn intersect(self, mut other: Self) -> Self {
346		let mut out = Self::new();
347		for v in self.0.into_iter() {
348			if let Some(pos) = other.iter().position(|w| v == *w) {
349				other.remove(pos);
350				out.push(v);
351			}
352		}
353		out
354	}
355}
356
357// ------------------------------
358
359// Documented with the assumption that it is just for arrays.
360pub(crate) trait Matches<T> {
361	/// Returns an array complimenting the original where each value is true or false
362	/// depending on whether it is == to the compared value.
363	///
364	/// Admittedly, this is most often going to be used in `count(array::matches($arr, $val))`
365	/// to count the number of times an element appears in an array but it's nice to have
366	/// this in addition.
367	fn matches(self, compare_val: Value) -> T;
368}
369
370impl Matches<Array> for Array {
371	fn matches(self, compare_val: Value) -> Array {
372		self.iter().map(|arr_val| (arr_val == &compare_val).into()).collect::<Vec<Value>>().into()
373	}
374}
375
376// ------------------------------
377
378// Documented with the assumption that it is just for arrays.
379pub(crate) trait Transpose<T> {
380	/// Stacks arrays on top of each other. This can serve as 2d array transposition.
381	///
382	/// The input array can contain regular values which are treated as arrays with
383	/// a single element.
384	///
385	/// It's best to think of the function as creating a layered structure of the arrays
386	/// rather than transposing them when the input is not a 2d array. See the examples
387	/// for what happense when the input arrays are not all the same size.
388	///
389	/// Here's a diagram:
390	/// [0, 1, 2, 3], [4, 5, 6]
391	/// ->
392	/// [0    | 1    | 2   |  3]
393	/// [4    | 5    | 6   ]
394	///  ^      ^      ^      ^
395	/// [0, 4] [1, 5] [2, 6] [3]
396	///
397	/// # Examples
398	///
399	/// ```ignore
400	/// fn array(sql: &str) -> Array {
401	///     unimplemented!();
402	/// }
403	///
404	/// // Example of `transpose` doing what it says on the tin.
405	/// assert_eq!(array("[[0, 1], [2, 3]]").transpose(), array("[[0, 2], [1, 3]]"));
406	/// // `transpose` can be thought of layering arrays on top of each other so when
407	/// // one array runs out, it stops appearing in the output.
408	/// assert_eq!(array("[[0, 1], [2]]").transpose(), array("[[0, 2], [1]]"));
409	/// assert_eq!(array("[0, 1, 2]").transpose(), array("[[0, 1, 2]]"));
410	/// ```
411	fn transpose(self) -> T;
412}
413
414impl Transpose<Array> for Array {
415	fn transpose(self) -> Array {
416		if self.is_empty() {
417			return self;
418		}
419		// I'm sure there's a way more efficient way to do this that I don't know about.
420		// The new array will be at *least* this large so we can start there;
421		let mut transposed_vec = Vec::<Value>::with_capacity(self.len());
422		let mut iters = self
423			.iter()
424			.map(|v| {
425				if let Value::Array(arr) = v {
426					Box::new(arr.iter().cloned()) as Box<dyn ExactSizeIterator<Item = Value>>
427				} else {
428					Box::new(std::iter::once(v).cloned())
429						as Box<dyn ExactSizeIterator<Item = Value>>
430				}
431			})
432			.collect::<Vec<_>>();
433		// We know there is at least one element in the array therefore iters is not empty.
434		// This is safe.
435		let longest_length = iters.iter().map(|i| i.len()).max().unwrap();
436		for _ in 0..longest_length {
437			transposed_vec
438				.push(iters.iter_mut().filter_map(|i| i.next()).collect::<Vec<_>>().into());
439		}
440		transposed_vec.into()
441	}
442}
443
444// ------------------------------
445
446pub(crate) trait Union<T> {
447	fn union(self, other: T) -> T;
448}
449
450impl Union<Self> for Array {
451	fn union(mut self, mut other: Self) -> Array {
452		self.append(&mut other);
453		self.uniq()
454	}
455}
456
457// ------------------------------
458
459pub(crate) trait Uniq<T> {
460	fn uniq(self) -> T;
461}
462
463impl Uniq<Array> for Array {
464	fn uniq(mut self) -> Array {
465		let mut set: HashSet<&Value> = HashSet::new();
466		let mut to_remove: Vec<usize> = Vec::new();
467		for (i, item) in self.iter().enumerate() {
468			if !set.insert(item) {
469				to_remove.push(i);
470			}
471		}
472		for i in to_remove.iter().rev() {
473			self.remove(*i);
474		}
475		self
476	}
477}